diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..26d33521af10bcc7fd8cea344038eaaeb78d0ef5 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/docs.iml b/.idea/docs.iml new file mode 100644 index 0000000000000000000000000000000000000000..d6ebd4805981b8400db3e3291c74a743fef9a824 --- /dev/null +++ b/.idea/docs.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000000000000000000000000000000000000..87ea532768b38bd5204c0ec5698088effb68bc8a --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,16 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000000000000000000000000000000000000..6049cfe013e0d2ef3f5f29c1b34b880e9d498ef0 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000000000000000000000000000000000000..35eb1ddfbbc029bcab630581847471d7f238ec53 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/CODEOWNERS b/CODEOWNERS index adfbdd2ec91d4b280aa5d5d9c39cd546ad84f7e9..0505a2b82d072e49f5bd1fb94a19fc2287c09f61 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -309,6 +309,8 @@ zh-cn/application-dev/reference/apis/js-apis-worker.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-xml.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-testRunner.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-uitest.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-hisysevent.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @zengyawen zh-cn/application-dev/quick-start/start-overview.md @ge-yafang zh-cn/application-dev/quick-start/start-with-ets.md @ge-yafang zh-cn/application-dev/quick-start/start-with-ets-low-code.md @ge-yafang diff --git a/README.md b/README.md index e5ec091688e68b4d3632dac4d6cd079ed8f0f279..7e19add93fd8c1818e41387bfd4c8ad34efa2b71 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ This repository stores device and application development documents provided by ## Contents +[OpenAtom OpenHarmony](https://www.openharmony.cn/docs?navId=3&navName=OpenHarmony%20Documentation%20Overview) + [Chinese Documentation](zh-cn/readme.md) [English Documentation](en/readme.md) @@ -15,7 +17,7 @@ This repository stores device and application development documents provided by ### Latest Versions - master: the latest version. - + - OpenHarmony 3.2 Beta1. [Learn more](en/release-notes/OpenHarmony-v3.2-beta1.md) - OpenHarmony 3.1 Release. [Learn more](en/release-notes/OpenHarmony-v3.1-release.md) diff --git a/en/OpenHarmony-Overview.md b/en/OpenHarmony-Overview.md index 685c1cd2bbb103470cd21df3150ffe948e51e769..c9eff6c8fe752a73cc4b8a2837ffe2a8ee7c0f0f 100644 --- a/en/OpenHarmony-Overview.md +++ b/en/OpenHarmony-Overview.md @@ -12,22 +12,22 @@ OpenHarmony is designed with a layered architecture, which from bottom to top, c **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: -- Basic system capability subsystem set: Implements distributed app running, scheduling, and migration across OpenHarmony devices. This subsystem set provides the following basic capabilities: Intelligent Soft Bus, distributed data management, Distributed Scheduler, Utils, multimodal input, graphics, security, and AI. +- 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 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, 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. @@ -42,81 +42,78 @@ This layer consists of system apps and third-party apps. Each OpenHarmony app is ## Technical Features -1. **Hardware collaboration and resource sharing** +**Hardware collaboration and resource sharing** - This feature is implemented through the following modules: +This feature is implemented through the following modules: - - Intelligent Soft Bus +- DSoftBus - Intelligent Soft Bus 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 data management - - Intelligent Soft Bus 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. +- 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 - - The Distributed Scheduler is designed based on technical features such as Intelligent Soft Bus, 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. +**One-time development for multi-device deployment** - - 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. +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. +Consistent APIs ensure the operational compatibility of apps across devices. -2. **One-time development for multi-device deployment** +- 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. - 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. +**A unified OS for flexible deployment** - Consistent APIs ensure the operational compatibility of apps 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. - -3. **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. +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 OpenHarmony supports the following 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 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. -- 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 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. -- 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 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. ## 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 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. -- Module +- Module - 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 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. 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| | -------- | -------- | -------- | -| 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 | -| DFileSystem | Provides APIs for synchronizing local JS files. | Standard system | +| 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 Hardware Driver Foundation (HDF). | 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 | @@ -125,14 +122,14 @@ The following table describes the subsystems of OpenHarmony. For details about t | 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 | +| 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 | -| Event 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 | +| 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, uninstallation, update, and query capabilities. | All systems | +| 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 | diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index 36d653078e36493e3927053cb636ba48062213d9..c964b95235cde910b76cde78f114772237973af4 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -20,24 +20,23 @@ - Development - [Ability Development](ability/Readme-EN.md) - [UI Development](ui/Readme-EN.md) - - Basic Feature Development - - [Common Event and Notification](notification/Readme-EN.md) - - [Window Manager](windowmanager/Readme-EN.md) - - [WebGL](webgl/Readme-EN.md) - - [Media](media/Readme-EN.md) - - [Security](security/Readme-EN.md) - - [Connectivity](connectivity/Readme-EN.md) - - [Data Management](database/Readme-EN.md) - - [Telephony](telephony/Readme-EN.md) - - [Agent-Powered Scheduled Reminders](background-agent-scheduled-reminder/Readme-EN.md) - - [Background Task Management](background-task-management/Readme-EN.md) - - [Work Scheduler](work-scheduler/Readme-EN.md) - - [Device Management](device/Readme-EN.md) - - [Device Usage Statistics](device-usage-statistics/Readme-EN.md) - - [DFX](dfx/Readme-EN.md) - - [Internationalization](internationalization/Readme-EN.md) - - [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) - - [Using Native APIs in Application Projects](napi/Readme-EN.md) + - [Common Event and Notification](notification/Readme-EN.md) + - [Window Manager](windowmanager/Readme-EN.md) + - [WebGL](webgl/Readme-EN.md) + - [Media](media/Readme-EN.md) + - [Security](security/Readme-EN.md) + - [Connectivity](connectivity/Readme-EN.md) + - [Data Management](database/Readme-EN.md) + - [Telephony](telephony/Readme-EN.md) + - [Agent-Powered Scheduled Reminders](background-agent-scheduled-reminder/Readme-EN.md) + - [Background Task Management](background-task-management/Readme-EN.md) + - [Work Scheduler](work-scheduler/Readme-EN.md) + - [Device Management](device/Readme-EN.md) + - [Device Usage Statistics](device-usage-statistics/Readme-EN.md) + - [DFX](dfx/Readme-EN.md) + - [Internationalization](internationalization/Readme-EN.md) + - [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) + - [Using Native APIs in Application Projects](napi/Readme-EN.md) - Tools - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) - Hands-On Tutorials @@ -47,7 +46,7 @@ - [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 (eTS Included) APIs](reference/apis/Readme-EN.md) + - [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) diff --git a/en/application-dev/ability/ability-delegator.md b/en/application-dev/ability/ability-delegator.md index 4e27041093bc2b9d1e3a2966f7a5f20b0f51b94c..5fd0293efde6d6d264be28b6c30123e7697bee6b 100644 --- a/en/application-dev/ability/ability-delegator.md +++ b/en/application-dev/ability/ability-delegator.md @@ -12,8 +12,8 @@ The APIs provided by the test framework can be used only in the test HAP. They t The test framework can be started in either of the following ways: -- Method 1: Run the aa test command. -- Method 2: Use the IDE. +- Method 1: Run the `aa test` command. +- Method 2: Use DevEco Studio. ### Running aa test @@ -37,16 +37,16 @@ aa test -b BundleName -m com.example.myapplicationfaets -s unittest OpenHarmonyT | -s unittest | Yes | Name of the **TestRunner** to be used. The TestRunner name must be the same as the file name. | | -w | No | Timeout interval of a test case, in seconds. If this parameter is not specified or is set to a value less than or equal to **0**, the test framework exits only after **finishTest** is invoked.| | -s \\ | No | **-s** can be followed by any key-value pair obtained through **AbilityDelegatorArgs.parameters**. For example, in **-s classname myTest**, **-s classname** is the key and **myTest** is the value.| -| -D | No | Debug mode for starting the tested application. | -| -h | No | Help information. | +| -D | No | Debug mode for starting the tested application.| +| -h | No | Help information.| -### Using the IDE +### Using DevEco Studio -For details about how to use the IDE to start the test framework, see [IDE Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-openharmony-test-framework-0000001263160453#section1034420367508). +For details about how to use DevEco Studio to start the test framework, see [OpenHarmony Test Framework](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-openharmony-test-framework-0000001263160453#section1034420367508). ## Introduction to TestRunner -**TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and override the **onPrepare** and **onRun** APIs. When creating an application template, the IDE initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-testRunner.md). +**TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and override the **onPrepare** and **onRun** APIs. When creating an application template, DevEco Studio initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-testRunner.md). ## Introduction to AbilityDelegatorRegistry @@ -136,6 +136,7 @@ abilityDelegator.startAbility(want, (err, data) => { ### Running a Shell Command **AbilityDelegator** provides APIs to run shell commands in the test environment. + **Example** ```javascript @@ -150,6 +151,7 @@ abilityDelegator.executeShellCommand(cmd, (err, data) => { ### Printing Log Information **AbilityDelegator** provides APIs for printing log information. You can call any API in the test code to print process logs to the unit test console. + **Example** ```javascript @@ -165,6 +167,7 @@ abilityDelegator.print(msg, (err) => { ### Finishing the Test and Printing Log Information **AbilityDelegator** provides the APIs for actively finishing the test. You can call any API in test code to finish the test and print logs to the unit test console. + **Example** ```javascript diff --git a/en/application-dev/ability/context-userguide.md b/en/application-dev/ability/context-userguide.md index 9c19655b7e0f1a7ff58a1a44cb3df43c827ee2c6..b058e9942bc7126c0a4b04a91acbd8806e9afdc4 100644 --- a/en/application-dev/ability/context-userguide.md +++ b/en/application-dev/ability/context-userguide.md @@ -195,7 +195,7 @@ export default class MainAbility extends Ability { ### application/FormExtensionContext -For details, see [FormExtensionContext](/en/application-dev/reference/apis/js-apis-formextensioncontext.md). +For details, see [FormExtensionContext](../reference/apis/js-apis-formextensioncontext.md). ## Common Incorrect Usage diff --git a/en/application-dev/ability/fa-dataability.md b/en/application-dev/ability/fa-dataability.md index 4b098d095df7ca0bec73c485f1a83d70ae43fb3d..f7bcf858e15b2f7f16b0327b1b91097e2f28facd 100644 --- a/en/application-dev/ability/fa-dataability.md +++ b/en/application-dev/ability/fa-dataability.md @@ -6,32 +6,40 @@ Data ability providers can customize data access-related APIs such as data inser ## Available APIs -**Table 1** Data ability lifecycle callbacks +**Table 1** Data ability lifecycle APIs |API|Description| |:------|:------| -|onInitialized|Called during ability initialization to initialize the relational database (RDB).| -|update|Updates data in the database.| -|query|Queries data in the database.| -|delete|Deletes one or multiple data records from the database.| -|normalizeUri|Normalizes the URI. A normalized URI applies to cross-device use, persistence, backup, and restore. When the context changes, it ensures that the same data item can be referenced.| -|batchInsert|Inserts multiple data records into the database.| -|denormalizeUri|Converts a normalized URI generated by **normalizeUri** into a denormalized URI.| -|insert|Inserts a data record into the database.| -|openFile|Opens a file.| -|getFileTypes|Obtains the MIME type of a file.| -|getType|Obtains the MIME type matching the data specified by the URI.| -|executeBatch|Operates data in the database in batches.| -|call|A customized API.| +|onInitialized?(info: AbilityInfo): void|Called during ability initialization to initialize the relational database (RDB).| +|update?(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\): void|Updates data in the database.| +|query?(uri: string, columns: Array\, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\): void|Queries data in the database.| +|delete?(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\): void|Deletes one or more data records from the database.| +|normalizeUri?(uri: string, callback: AsyncCallback\): void|Normalizes the URI. A normalized URI applies to cross-device use, persistence, backup, and restore. When the context changes, it ensures that the same data item can be referenced.| +|batchInsert?(uri: string, valueBuckets: Array\, callback: AsyncCallback\): void|Inserts multiple data records into the database.| +|denormalizeUri?(uri: string, callback: AsyncCallback\): void|Converts a normalized URI generated by **normalizeUri** into a denormalized URI.| +|insert?(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback\): void|Inserts a data record into the database.| +|openFile?(uri: string, mode: string, callback: AsyncCallback\): void|Opens a file.| +|getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback\>): void|Obtains the MIME type of a file.| +|getType?(uri: string, callback: AsyncCallback\): void|Obtains the MIME type matching the data specified by the URI.| +|executeBatch?(ops: Array\, callback: AsyncCallback\>): void|Operates data in the database in batches.| +|call?(method: string, arg: string, extras: PacMap, callback: AsyncCallback\): void|Calls a custom API.| ## How to Develop ### Creating a Data Ability -1. To meet the basic requirements of the database storage service, implement the **Insert**, **Query**, **Update**, and **Delete** APIs in the **Data** class to provide batch data processing. The traversal logic has been implemented by the **BatchInsert** and **ExecuteBatch** APIs. +1. To meet the basic requirements of the database storage service, implement the **Insert**, **Query**, **Update**, and **Delete** APIs in the **Data** class. The **BatchInsert** and **ExecuteBatch** APIs have already implemented the traversal logic, but not batch data processing. The following code snippet shows how to create a Data ability: ```javascript + import dataAbility from '@ohos.data.dataAbility' + import dataRdb from '@ohos.data.rdb' + + const TABLE_NAME = 'book' + const STORE_CONFIG = { name: 'book.db' } + const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, introduction TEXT NOT NULL)' + let rdbStore: dataRdb.RdbStore = undefined + export default { onInitialized(abilityInfo) { console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName) @@ -50,7 +58,7 @@ Data ability providers can customize data access-related APIs such as data inser for (let i = 0;i < valueBuckets.length; i++) { console.info('DataAbility batch insert i=' + i) if (i < valueBuckets.length - 1) { - rdbStore.insert(TABLE_NAME, valueBuckets[i], (num: number) => { + rdbStore.insert(TABLE_NAME, valueBuckets[i], (err: any, num: number) => { console.info('DataAbility batch insert ret=' + num) }) } else { @@ -76,7 +84,7 @@ Data ability providers can customize data access-related APIs such as data inser }; ``` -2. Submodule Configuration +2. Configure the submodule. | JSON Field| Description | | ------------ | ------------------------------------------------------------ | @@ -89,15 +97,15 @@ Data ability providers can customize data access-related APIs such as data inser ```json "abilities":[{ - "srcPath": "DataAbility", - "name": ".DataAbility", - "icon": "$media:icon", - "srcLanguage": "ets", - "description": "$string:description_dataability", - "type": "data", - "visible": true, - "uri": "dataability://ohos.samples.etsdataability.DataAbility" - }] + "srcPath": "DataAbility", + "name": ".DataAbility", + "icon": "$media:icon", + "srcLanguage": "ets", + "description": "$string:description_dataability", + "type": "data", + "visible": true, + "uri": "dataability://ohos.samples.etsdataability.DataAbility" + }] ``` ### Accessing a Data ability @@ -118,6 +126,10 @@ The basic dependency packages include: For details about the APIs provided by **DataAbilityHelper**, see [DataAbilityHelper Module](../reference/apis/js-apis-dataAbilityHelper.md). ```js // Different from the URI defined in the config.json file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). + import featureAbility from '@ohos.ability.featureAbility' + import ohos_data_ability from '@ohos.data.dataAbility' + import ohos_data_rdb from '@ohos.data.rdb' + var urivar = "dataability:///com.ix.DataAbility" var DAHelper = featureAbility.acquireDataAbilityHelper( urivar @@ -137,7 +149,7 @@ The basic dependency packages include: urivar, valuesBucket, (error, data) => { - expect(typeof(data)).assertEqual("number") + console.log("DAHelper insert result: " + data) } ); ``` @@ -156,7 +168,7 @@ The basic dependency packages include: urivar, da, (error, data) => { - expect(typeof(data)).assertEqual("number") + console.log("DAHelper delete result: " + data) } ); ``` @@ -176,7 +188,7 @@ The basic dependency packages include: valuesBucket, da, (error, data) => { - expect(typeof(data)).assertEqual("number") + console.log("DAHelper update result: " + data) } ); ``` @@ -197,7 +209,7 @@ The basic dependency packages include: valArray, da, (error, data) => { - expect(typeof(data)).assertEqual("object") + console.log("DAHelper query result: " + data) } ); ``` @@ -217,7 +229,7 @@ The basic dependency packages include: urivar, cars, (error, data) => { - expect(typeof(data)).assertEqual("number") + console.log("DAHelper batchInsert result: " + data) } ); ``` @@ -241,12 +253,12 @@ The basic dependency packages include: valuesBucket: {"executeBatch" : "value1",}, predicates: da, expectedCount:0, - PredicatesBackReferences: {}, + predicatesBackReferences: null, interrupted:true, } ], (error, data) => { - expect(typeof(data)).assertEqual("object") + console.log("DAHelper executeBatch result: " + data) } ); ``` @@ -265,21 +277,15 @@ The basic dependency packages include: }, predicates: da, expectedCount:0, - PredicatesBackReferences: {}, + predicatesBackReferences: null, interrupted:true, } ] ); ``` -## Development Example - -The following sample is provided to help you better understand how to develop a Data ability: - -- [DataAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/DataAbility) - -This sample shows how to: +## Samples -Create a Data ability in the **data.ts** file in the **DataAbility** directory. +The following sample is provided to help you better understand how to develop Data abilities: -Encapsulate the process of accessing the Data ability in the **MainAbility** directory. +- [`DataAbility`: Creation and Access of Data Abilities (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DataAbility) diff --git a/en/application-dev/ability/fa-formability.md b/en/application-dev/ability/fa-formability.md index 8b447ba835d915e3d6ff1b7ed491342932048673..dac8d5ee66e4441021a91f1967815d364227228c 100644 --- a/en/application-dev/ability/fa-formability.md +++ b/en/application-dev/ability/fa-formability.md @@ -3,20 +3,12 @@ ## Widget Overview A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application. -A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive features such as opening a UI page or sending a message. The widget host is responsible for displaying the widget. +A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message. Basic concepts: -- Widget provider - - The widget provider is an atomic service that provides the content to be displayed. It controls the display content, component layout, and component click events of a widget. - -- Widget host - - The widget host is an application that displays the widget content and controls the position where the widget is displayed in the host application. - -- Widget Manager - - The Widget Manager is a resident agent that manages widgets added to the system and provides functions such as periodic widget update. +- Widget provider: an atomic service that controls what and how content is displayed in a widget and interacts with users. +- Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application. +- Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update. > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated. @@ -30,7 +22,7 @@ The widget provider controls the widget content to display, component layout, an Form ability development refers to the development conducted by the widget provider based on the [Feature Ability (FA) model](fa-brief.md). As a widget provider, you need to carry out the following operations: - Develop the lifecycle callbacks in **LifecycleForm**. -- Create a **FormBindingData** object. +- Create a **FormBindingData** instance. - Update a widget through **FormProvider**. - Develop the widget UI page. @@ -46,9 +38,9 @@ The table below describes the lifecycle callbacks provided **LifecycleForm**. | onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| | onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. | | onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change of widget visibility. | -| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process the widget event. | +| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event. | | onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. | -| onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a specified widget. | +| onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a widget. | For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md). @@ -81,7 +73,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li export default { onCreate(want) { console.log('FormAbility onCreate'); - // Persistently store widget information for subsequent use, such as widget instance retrieval and update. + // Persistently store widget information for subsequent use, such as during widget instance retrieval or update. let obj = { "title": "titleOnCreate", "detail": "detailOnCreate" @@ -94,7 +86,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li console.log('FormAbility onCastToNormal'); }, onUpdate(formId) { - // To support scheduled update, periodic update, or update requested by the widget host for a widget, override this method for data update. + // To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update. console.log('FormAbility onUpdate'); let obj = { "title": "titleOnUpdate", @@ -124,11 +116,11 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li } ``` -### Configuring config.json for the Form Ability +### Configuring the Widget Configuration File -Configure the **config.json** file for the **Form** ability. +Configure the **config.json** file for the widget. -- The **js** module in the **config.json** file provides the JavaScript resources of the **Form** ability. The internal field structure is described as follows: +- The **js** module in the **config.json** file provides the JavaScript resources of the widget. The internal field structure is described as follows: | Field| Description | Data Type| Default | | -------- | ------------------------------------------------------------ | -------- | ------------------------ | @@ -161,12 +153,12 @@ Configure the **config.json** file for the **Form** ability. | isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | | type | Type of the widget. Available values are as follows:
**JS**: indicates a JavaScript-programmed widget. | String | No | | colorMode | Color mode of the widget. Available values are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| - | supportDimensions | Grid styles supported by the widget. Available values are as follows:
1 * 2: indicates a grid with one row and two columns.
2 * 2: indicates a grid with two rows and two columns.
2 * 4: indicates a grid with two rows and four columns.
4 * 4: indicates a grid with four rows and four columns.| String array| No | + | supportDimensions | Grid styles supported by the widget. Available values are as follows:
**1 * 2**: indicates a grid with one row and two columns.
**2 * 2**: indicates a grid with two rows and two columns.
**2 * 4**: indicates a grid with two rows and four columns.
**4 * 4**: indicates a grid with four rows and four columns.| String array| No | | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | - | formConfigAbility | Indicates the link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | + | formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | | jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. | String | No | | metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) | @@ -203,7 +195,7 @@ Configure the **config.json** file for the **Form** ability. ``` -### Widget Data Persistence +### Persistently Store Widget Data Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget. @@ -215,6 +207,7 @@ Mostly, the widget provider is started only when it needs to obtain information let formName = want.parameters["ohos.extra.param.key.form_name"]; let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; // Persistently store widget information for subsequent use, such as widget instance retrieval and update. + // The storeFormInfo API is not implemented here. For details about the implementation, see "FA Model Widget" provided in "Samples". storeFormInfo(formId, formName, tempFlag, want); let obj = { @@ -230,26 +223,28 @@ You should override **onDestroy** to delete widget data. ```javascript onDestroy(formId) { - // Delete widget data. - deleteFormInfo(formId); console.log('FormAbility onDestroy'); + + // You need to implement the code for deleting the persistent widget instance. + // The deleteFormInfo API is not implemented here. For details, see "Widget Host" provided in "Samples". + deleteFormInfo(formId); } ``` For details about the persistence method, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one. + +- Normal widget: a widget that will be persistently used by the widget host -Normal widget: a widget that will be persistently used by the widget host - -Temporary widget: a widget that is temporarily used by the widget host +- Temporary widget: a widget that is temporarily used by the widget host Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget host may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets. ### Developing the Widget UI Page You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI. - HML: @@ -331,10 +326,8 @@ Now you've got a widget shown below. ![fa-form-example](figures/fa-form-example.png) -## Development Example - -The following sample is provided to help you better understand how to develop a widget on the FA model: - -[FormAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility) +## Samples -This sample provides a widget. Users can create, update, and delete widgets on the home screen of their devices or by using their own widget host. This sample also implements widget information persistence by using lightweight data storage. +The following samples are provided to help you better understand how to develop a widget on the FA model: +- [`FormAbility`: FA Model Widget (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility) +- [`FormLauncher`: Widget Host (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormLauncher) diff --git a/en/application-dev/ability/fa-pageability.md b/en/application-dev/ability/fa-pageability.md index beaac42b2915507ef9ff58a4e40790c458d43f7f..3c9fd320425f7b5fa961665aa104645d1dcbcebf 100644 --- a/en/application-dev/ability/fa-pageability.md +++ b/en/application-dev/ability/fa-pageability.md @@ -102,16 +102,16 @@ By default, **singleton** is used. console.info('onStartRemoteAbility begin'); let params; let wantValue = { - bundleName: 'ohos.samples.etsDemo', - abilityName: 'ohos.samples.etsDemo.RemoteAbility', - deviceId: getRemoteDeviceId(), - parameters: params + bundleName: 'ohos.samples.etsDemo', + abilityName: 'ohos.samples.etsDemo.RemoteAbility', + deviceId: getRemoteDeviceId(), + parameters: params }; console.info('onStartRemoteAbility want=' + JSON.stringify(wantValue)); featureAbility.startAbility({ - want: wantValue + want: wantValue }).then((data) => { - console.info('onStartRemoteAbility finished, ' + JSON.stringify(data)); + console.info('onStartRemoteAbility finished, ' + JSON.stringify(data)); }); console.info('onStartRemoteAbility end'); } @@ -123,17 +123,17 @@ Obtain **deviceId** from **DeviceManager**. The sample code is as follows: import deviceManager from '@ohos.distributedHardware.deviceManager'; let dmClass; function getRemoteDeviceId() { - if (typeof dmClass === 'object' && dmClass != null) { - let list = dmClass.getTrustedDeviceListSync(); - if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { + if (typeof dmClass === 'object' && dmClass != null) { + let list = dmClass.getTrustedDeviceListSync(); + if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null"); return; - } - console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); - return list[0].deviceId; - } else { - console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); - } + } + console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); + return list[0].deviceId; + } else { + console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); + } } ``` @@ -143,35 +143,34 @@ In the cross-device scenario, the application must also apply for the data synch import abilityAccessCtrl from "@ohos.abilityAccessCtrl"; import bundle from '@ohos.bundle'; async function RequestPermission() { - console.info('RequestPermission begin'); - let array: Array = ["ohos.permission.DISTRIBUTED_DATASYNC"]; - let bundleFlag = 0; - let tokenID = undefined; - let userID = 100; - let appInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', bundleFlag, userID); - tokenID = appInfo.accessTokenId; - let atManager = abilityAccessCtrl.createAtManager(); - let requestPermissions: Array = []; - for (let i = 0;i < array.length; i++) { - let result = await atManager.verifyAccessToken(tokenID, array[i]); - console.info("verifyAccessToken result:" + JSON.stringify(result)); - if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { - } else { - requestPermissions.push(array[i]); - } - } - console.info("requestPermissions:" + JSON.stringify(requestPermissions)); - if (requestPermissions.length == 0 || requestPermissions == []) { - return; - } - let context = featureAbility.getContext(); - context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{ - console.info("data:" + JSON.stringify(data)); - console.info("data requestCode:" + data.requestCode); - console.info("data permissions:" + data.permissions); - console.info("data authResults:" + data.authResults); - }); - console.info('RequestPermission end'); + console.info('RequestPermission begin'); + let array: Array = ["ohos.permission.DISTRIBUTED_DATASYNC"]; + let bundleFlag = 0; + let tokenID = undefined; + let userID = 100; + let appInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', bundleFlag, userID); + tokenID = appInfo.accessTokenId; + let atManager = abilityAccessCtrl.createAtManager(); + let requestPermissions: Array = []; + for (let i = 0;i < array.length; i++) { + let result = await atManager.verifyAccessToken(tokenID, array[i]); + console.info("verifyAccessToken result:" + JSON.stringify(result)); + if (result != abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { + requestPermissions.push(array[i]); + } + } + console.info("requestPermissions:" + JSON.stringify(requestPermissions)); + if (requestPermissions.length == 0 || requestPermissions == []) { + return; + } + let context = featureAbility.getContext(); + context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{ + console.info("data:" + JSON.stringify(data)); + console.info("data requestCode:" + data.requestCode); + console.info("data permissions:" + data.permissions); + console.info("data authResults:" + data.authResults); + }); + console.info('RequestPermission end'); } ``` diff --git a/en/application-dev/ability/fa-serviceability.md b/en/application-dev/ability/fa-serviceability.md index cf2609b22be6082751f415a6d85aac20e1a8ec9a..ef62358595f235aeae23d1f4b0bb63cb77936537 100644 --- a/en/application-dev/ability/fa-serviceability.md +++ b/en/application-dev/ability/fa-serviceability.md @@ -5,22 +5,20 @@ A Service ability is used to run tasks in the background, such as playing music ## Available APIs -**Table 1** Service ability lifecycle callbacks +**Table 1** Service ability lifecycle APIs |API|Description| |:------|:------| -|onStart|Called to initialize a Service ability when the Service ability is being created. This callback is invoked only once in the entire lifecycle of a Service ability. The **Want** object passed to this callback must be null.| -|onCommand|Called every time a Service ability is created on a client. You can calculate calling statistics and perform initialization operations in this callback.| -|onConnect|Called when another ability is connected to the Service ability.| -|onDisconnect|Called when another ability is disconnected from the Service ability.| -|onStop|Called when the Service ability is being destroyed. You should override this callback for your Service ability to clear its resources, such as threads and registered listeners.| +|onStart?(): void|Called to initialize a Service ability being created. This callback is invoked only once in the entire lifecycle of a Service ability. The **Want** object passed to this callback must be null.| +|onCommand?(want: Want, startId: number): void|Called every time a Service ability is created on a client. You can collect calling statistics and perform initialization operations in this callback.| +|onConnect?(want: Want): rpc.RemoteObject|Called when another ability is connected to the Service ability.| +|onDisconnect?(want: Want): void|Called when another ability is disconnected from the Service ability.| +|onStop?(): void|Called when the Service ability is being destroyed. You should override this callback for your Service ability to clear its resources, such as threads and registered listeners.| ## How to Develop -### Creating a Service Ability +### Creating and Registering a Service Ability -1. Create a child class of the **Ability** class and override the following Service ability-related lifecycle callbacks to implement your own logic for processing requests to interact with your Service ability: - - The following code snippet shows how to create a Service ability: +1. Override the Service ability-related lifecycle callbacks to implement your own logic for processing interaction requests. ```javascript export default { @@ -32,6 +30,7 @@ A Service ability is used to run tasks in the background, such as playing music }, onConnect(want) { console.log('ServiceAbility OnConnect'); + return null; }, onDisconnect(want) { console.log('ServiceAbility OnDisConnect'); @@ -41,10 +40,10 @@ A Service ability is used to run tasks in the background, such as playing music }, } ``` - + 2. Register a Service ability. - You must declare your Service ability in the **config.json** file by setting its **type** attribute to **service**. + Declare the Service ability in the **config.json** file by setting its **type** attribute to **service**. ```javascript { @@ -78,12 +77,12 @@ The following code snippet shows how to start a Service ability running on the l ```javascript import featureAbility from '@ohos.ability.featureAbility'; -let promise = await featureAbility.startAbility( +let promise = featureAbility.startAbility( { want: { - bundleName: "com.jstest.serviceability", - abilityName: "com.jstest.serviceability.MainAbility", + bundleName: "com.jstest.service", + abilityName: "com.jstest.service.ServiceAbility", }, } ); @@ -93,11 +92,26 @@ After the preceding code is executed, the **startAbility()** API is called to st - If the Service ability is not running, the system calls **onStart()** to initialize the Service ability, and then calls **onCommand()** on the Service ability. - If the Service ability is running, the system directly calls **onCommand()** on the Service ability. +The following code snippet shows how to start a Service ability running on the remote device. For details about **getRemoteDeviceId()**, see [Connecting to a Remote Service Ability](#connecting-to-a-remote-service-ability-applying-only-to-system-applications). + +```javascript +import featureAbility from '@ohos.ability.featureAbility'; +let promise = featureAbility.startAbility( + { + want: + { + deviceId: getRemoteDeviceId(), // Remote device ID + bundleName: "com.jstest.service", + abilityName: "com.jstest.service.ServiceAbility", + }, + } +); +``` ### Stopping a Service Ability - Once created, the Service ability keeps running in the background. The system does not stop or destroy it unless memory resources must be reclaimed. You can call **terminateSelf()** on a Service ability to stop it. +Once created, the Service ability keeps running in the background. The system does not stop or destroy it unless memory resources must be reclaimed. @@ -105,124 +119,140 @@ After the preceding code is executed, the **startAbility()** API is called to st If you need to connect a Service ability to a Page ability or to a Service ability in another application, you must first implement the **IAbilityConnection** API for the connection. A Service ability allows other abilities to connect to it through **connectAbility()**. -When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails. -The following code snippet shows how to implement the callbacks: +You can use either of the following methods to connect to a Service ability: -```javascript -let mRemote; -function onConnectCallback(element, remote){ - console.log('onConnectLocalService onConnectDone element: ' + element); - console.log('onConnectLocalService onConnectDone remote: ' + remote); - mRemote = remote; - if (mRemote == null) { - prompt.showToast({ - message: "onConnectLocalService not connected yet" - }); - return; - } - let option = new rpc.MessageOption(); - let data = new rpc.MessageParcel(); - let reply = new rpc.MessageParcel(); - data.writeInt(1); - data.writeInt(99); - mRemote.sendRequest(1, data, reply, option).then((result) => { - console.log('sendRequest success'); - let msg = reply.readInt(); +1. Using the IDL to automatically generate code + + Use OpenHarmony Interface Definition Language (IDL) to automatically generate the corresponding client, server, and **IRemoteObject** code. For details, see [“Development Using TS” in OpenHarmony IDL Specifications and User Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/IDL/idl-guidelines.md#development-using-ts). + +2. Writing code in the corresponding file + + When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails. + + The following code snippet shows how to implement the callbacks: + + ```javascript + import prompt from '@system.prompt' + + let mRemote; + function onConnectCallback(element, remote){ + console.log('onConnectLocalService onConnectDone element: ' + element); + console.log('onConnectLocalService onConnectDone remote: ' + remote); + mRemote = remote; + if (mRemote == null) { prompt.showToast({ - message: "onConnectLocalService connect result: " + msg, - duration: 3000 + message: "onConnectLocalService not connected yet" + }); + return; + } + let option = new rpc.MessageOption(); + let data = new rpc.MessageParcel(); + let reply = new rpc.MessageParcel(); + data.writeInt(1); + data.writeInt(99); + mRemote.sendRequest(1, data, reply, option).then((result) => { + console.log('sendRequest success'); + let msg = reply.readInt(); + prompt.showToast({ + message: "onConnectLocalService connect result: " + msg, + duration: 3000 + }); + }).catch((e) => { + console.log('sendRequest error:' + e); }); - }).catch((e) => { - console.log('sendRequest error:' + e); - }); -} + } -function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect Callback') -} + function onDisconnectCallback(element){ + console.log('ConnectAbility onDisconnect Callback') + } -function onFailedCallback(code){ - console.log('ConnectAbility onFailed Callback') -} -``` + function onFailedCallback(code){ + console.log('ConnectAbility onFailed Callback') + } + ``` -The following code snippet shows how to connect to a local Service ability: + The following code snippet shows how to connect to a local Service ability: -```javascript -import featureAbility from '@ohos.ability.featureAbility'; -let connId = featureAbility.connectAbility( - { - bundleName: "com.jstest.serviceability", - abilityName: "com.jstest.serviceability.MainAbility", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, -); -``` + ```javascript + import featureAbility from '@ohos.ability.featureAbility'; + let connId = featureAbility.connectAbility( + { + bundleName: "com.jstest.service", + abilityName: "com.jstest.service.ServiceAbility", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, + ); + ``` -When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of the **IRemoteObject** interface. You can inherit **rpc.RemoteObject** to implement your own class of **IRemoteObject**. + When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of **IRemoteObject**. You can extend **rpc.RemoteObject** to implement your own class of **IRemoteObject**. -The following code snippet shows how the Service ability instance returns itself to the calling ability: + The following code snippet shows how the Service ability instance returns itself to the calling ability: -```javascript -import rpc from "@ohos.rpc"; + ```javascript + import rpc from "@ohos.rpc"; -let mMyStub; -export default { - onStart() { - class MyStub extends rpc.RemoteObject{ - constructor(des) { - if (typeof des === 'string') { - super(des); + let mMyStub; + export default { + onStart() { + class MyStub extends rpc.RemoteObject{ + constructor(des) { + if (typeof des === 'string') { + super(des); + } + return null; } - return null; - } - onRemoteRequest(code, data, reply, option) { - console.log("ServiceAbility onRemoteRequest called"); - if (code === 1) { - let op1 = data.readInt(); - let op2 = data.readInt(); - console.log("op1 = " + op1 + ", op2 = " + op2); - reply.writeInt(op1 + op2); - } else { - console.log("ServiceAbility unknown request code"); + onRemoteRequest(code, data, reply, option) { + console.log("ServiceAbility onRemoteRequest called"); + if (code === 1) { + let op1 = data.readInt(); + let op2 = data.readInt(); + console.log("op1 = " + op1 + ", op2 = " + op2); + reply.writeInt(op1 + op2); + } else { + console.log("ServiceAbility unknown request code"); + } + return true; } - return true; } - } - mMyStub = new MyStub("ServiceAbility-test"); - }, - onCommand(want, startId) { - console.log('ServiceAbility onCommand'); - }, - onConnect(want) { - console.log('ServiceAbility OnConnect'); - return mMyStub; - }, - onDisconnect(want) { - console.log('ServiceAbility OnDisConnect'); - }, - onStop() { - console.log('ServiceAbility onStop'); - }, -} -``` + mMyStub = new MyStub("ServiceAbility-test"); + }, + onCommand(want, startId) { + console.log('ServiceAbility onCommand'); + }, + onConnect(want) { + console.log('ServiceAbility OnConnect'); + return mMyStub; + }, + onDisconnect(want) { + console.log('ServiceAbility OnDisConnect'); + }, + onStop() { + console.log('ServiceAbility onStop'); + }, + } + ``` + +### Connecting to a Remote Service Ability (Applying only to System Applications) -### Connecting to a Remote Service Ability (Applying only to System Applications) ->Note: The **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. Therefore, remote Service ability startup applies only to system applications. +>**NOTE** +> +>This feature applies only to system applications, since the **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. -If you need to connect a Service ability to a Page ability on another device or to a Service ability in another application on another device, you must first implement the **IAbilityConnection** interface for the connection. A Service ability allows other abilities on another device to connect to it through **connectAbility()**. +If you need to connect a Service ability to a Page ability or another Service ability on a remote device, you must first implement the **IAbilityConnection** interface for the connection. A Service ability allows abilities on another device to connect to it through **connectAbility()**. When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails. The following code snippet shows how to implement the callbacks: ```ts +import prompt from '@system.prompt' + let mRemote; function onConnectCallback(element, remote){ console.log('onConnectRemoteService onConnectDone element: ' + element); @@ -264,7 +294,10 @@ The **Want** of the target Service ability must contain the remote **deviceId**, ```ts import deviceManager from '@ohos.distributedHardware.deviceManager'; + +// For details about the implementation of dmClass, see the implementation in Distributed Demo in Samples. let dmClass; + function getRemoteDeviceId() { if (typeof dmClass === 'object' && dmClass != null) { let list = dmClass.getTrustedDeviceListSync(); @@ -327,15 +360,12 @@ async function RequestPermission() { let context = featureAbility.getContext(); context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{ console.info("data:" + JSON.stringify(data)); - console.info("data requestCode:" + data.requestCode); - console.info("data permissions:" + data.permissions); - console.info("data authResults:" + data.authResults); }); console.info('RequestPermission end'); } ``` -When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of the **IRemoteObject** interface. You can inherit **rpc.RemoteObject** to implement your own class of **IRemoteObject**. +When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of **IRemoteObject**. You can extend **rpc.RemoteObject** to implement your own class of **IRemoteObject**. The following code snippet shows how the Service ability instance returns itself to the calling ability: @@ -398,5 +428,5 @@ export default { ## Samples The following samples are provided to help you better understand how to develop a Service ability: -- [`ServiceAbility`: Service Ability Creation and Use (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceAbility) -- [`DMS`: Distributed Demo (eTS) (API7)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS) +- [`ServiceAbility`: Service Ability Creation and Use (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceAbility) +- [`DMS`: Distributed Demo (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS) diff --git a/en/application-dev/ability/stage-ability-continuation.md b/en/application-dev/ability/stage-ability-continuation.md index 0e070f2fee46ba41aa1f7c342b202010a9b58d10..0695a3bd491785d414d75be6520d513229b0bcbc 100644 --- a/en/application-dev/ability/stage-ability-continuation.md +++ b/en/application-dev/ability/stage-ability-continuation.md @@ -2,19 +2,18 @@ ## When to Use -Ability continuation is to continue the current mission of an application, including the UI component status variables and distributed objects, on another device. The UI component status variables are used to synchronize page data, and the distributed objects are used to synchronize data in the memory. +Ability continuation is to continue the current mission of an application, including the UI component state variables and distributed objects, on another device. The UI component state variables are used to synchronize UI data, and the distributed objects are used to synchronize memory data. ## Available APIs -The following table lists the APIs used for ability continuation. For details about the APIs, see [Ability](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-application-ability.md). +The following table lists the APIs used for ability continuation. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md). **Table 1** Ability continuation APIs |API| Description| |:------ | :------| -| onContinue(wantParam : {[key: string]: any}): OnContinueResult | Called by the **initiator** to save data during the ability continuation preparation process. The return value **0** means that the continuation request is accepted, and an error code means that the continuation request is denied.| -| onCreate(want: Want, param: LaunchParam): void| Called by the **target** to restore the data and page.| -| **enum** OnContinueResult | Enumerates the return values of **onContinue**. The options are as follows: **AGREE** (request accepted), **REJECT** (request denied), and **MISMATCH** (version mismatch).| +| onContinue(wantParam : {[key: string]: any}): OnContinueResult | Called by the initiator to store the data required for continuation and request continuation. The value **AGREE** means that the continuation is accepted, and **REJECT** means the continuation is rejected, and **MISMATCH** means a version mismatch.| +| onCreate(want: Want, param : LaunchParam): void | Called by the target to restore the data and UI page.| @@ -22,6 +21,8 @@ The following table lists the APIs used for ability continuation. For details ab ![continuation_dev](figures/continuation-info.png) +In effect, ability continuation is a cross-device ability startup that carries data. When the continuation is triggered, device A calls back **onContinue()** of the application. You must save the current data in this API. Then, device A initiates a cross-device ability startup on device B and transmits the data to device B. Device B calls back **onCreate()**. You must restore the transmitted data in this API. + ## How to Develop ### Application Continuation @@ -31,78 +32,84 @@ The following table lists the APIs used for ability continuation. For details ab - Configure the application to support ability continuation. Set the **continuable** field in the **module.json5** file to **true**. The default value is **false**. If this parameter is set to **false**, the application cannot be continued on another device. - - ```javascript - "continuable": true - ``` + + ```javascript + "continuable": true + ``` + - * Configure the application startup type. + - Configure the application startup type. - Set **launchType** in the **module.json5** to **standard**. Currently, only multi-instance applications can be continued on another device. - - ```javascript - "launchType": "standard" - ``` + Set **launchType** in the **module.json5** file to **standard** to add multi-instance support to the application. + + ```javascript + "launchType": "standard" + ``` + - * Apply for the distributed permissions. + - Apply for the distributed permissions. Declare the **DISTRIBUTED_DATASYNC** permission in the **module.json5** file for the application. - - ```javascript - "requestPermissions": [ - { - "name": "ohos.permission.DISTRIBUTED_DATASYNC" - }, - ``` - - This permission must be granted by the user in a dialog box when the application is started for the first time. To enable the application to display a dialog box to ask for the permission, add the following code to **onWindowStageCreate** of the **Ability** class: - - ```javascript - requestPermissions = async () => { - let permissions: Array = [ - "ohos.permission.DISTRIBUTED_DATASYNC" - ]; - let needGrantPermission = false - let accessManger = accessControl.createAtManager() - Logger.info("app permission get bundle info") - let bundleInfo = await bundle.getApplicationInfo(BUNDLE_NAME, 0, 100) - Logger.info(`app permission query permission ${bundleInfo.accessTokenId.toString()}`) - for (const permission of permissions) { - Logger.info(`app permission query grant status ${permission}`) - try { - let grantStatus = await accessManger.verifyAccessToken(bundleInfo.accessTokenId, permission) - if (grantStatus === PERMISSION_REJECT) { - needGrantPermission = true - break; - } - } catch (err) { - Logger.error(`app permission query grant status error ${permission} ${JSON.stringify(err)}`) - needGrantPermission = true - break; - } - } - if (needGrantPermission) { - Logger.info("app permission needGrantPermission") - try { - await this.context.requestPermissionsFromUser(permissions) - } catch (err) { - Logger.error(`app permission ${JSON.stringify(err)}`) - } - } else { - Logger.info("app permission already granted") - } - } - ``` - - - -2. Implement the **onContinue** API. - - The **onContinue** API is called by the **initiator** to save the UI component status variables and memory data and prepare for continuation. After the application completes the continuation preparation, the system must return **OnContinueResult.AGREE** to accept the continuation request. If an error code is returned, the request is denied. If this API is not implemented, the system rejects the continuation request by default. + + ```javascript + "requestPermissions": [ + { + "name": "ohos.permission.DISTRIBUTED_DATASYNC" + }, + ``` + + + + This permission must be granted by the user in a dialog box when the application is started for the first time. To enable the application to display a dialog box to ask for the permission, add the following code to **onWindowStageCreate** of the **Ability** class: + + ```javascript + requestPermissions = async () => { + let permissions: Array = [ + "ohos.permission.DISTRIBUTED_DATASYNC" + ]; + let needGrantPermission = false + let accessManger = accessControl.createAtManager() + Logger.info("app permission get bundle info") + let bundleInfo = await bundle.getApplicationInfo(BUNDLE_NAME, 0, 100) + Logger.info(`app permission query permission ${bundleInfo.accessTokenId.toString()}`) + for (const permission of permissions) { + Logger.info(`app permission query grant status ${permission}`) + try { + let grantStatus = await accessManger.verifyAccessToken(bundleInfo.accessTokenId, permission) + if (grantStatus === PERMISSION_REJECT) { + needGrantPermission = true + break; + } + } catch (err) { + Logger.error(`app permission query grant status error ${permission} ${JSON.stringify(err)}`) + needGrantPermission = true + break; + } + } + if (needGrantPermission) { + Logger.info("app permission needGrantPermission") + try { + await this.context.requestPermissionsFromUser(permissions) + } catch (err) { + Logger.error(`app permission ${JSON.stringify(err)}`) + } + } else { + Logger.info("app permission already granted") + } + } + ``` + + + + + +2. Implement the **onContinue()** API. + + The **onContinue()** API is called by the initiator to save the UI component state variables and memory data and prepare for continuation. After the application completes the continuation preparation, the system must return **OnContinueResult.AGREE(0)** to accept the continuation request. If an error code is returned, the request is rejected. If this API is not implemented, the system rejects the continuation request by default. Modules to import: @@ -111,41 +118,38 @@ The following table lists the APIs used for ability continuation. For details ab import AbilityConstant from '@ohos.application.AbilityConstant'; ``` - - To implement ability continuation, you must implement this API and have the value **AGREE** returned. - - - - Example - + To implement ability continuation, you must implement this API and have the value **AGREE** returned. + + Example + ```javascript - onContinue(wantParam : {[key: string]: any}) { - Logger.info("onContinue using distributedObject") - // Set the user input data into the want parameter. - wantParam["input"] = AppStorage.Get('ContinueInput'); - Logger.info(`onContinue input = ${wantParam["input"]}`); - return AbilityConstant.OnContinueResult.AGREE - } + onContinue(wantParam : {[key: string]: any}) { + Logger.info("onContinue using distributedObject") + // Set the user input data into want params. + wantParam["input"] = AppStorage.Get('ContinueInput'); + Logger.info(`onContinue input = ${wantParam["input"]}`); + return AbilityConstant.OnContinueResult.AGREE + } ``` + + +3. Implement the continuation logic in the **onCreate()** API. + The **onCreate()** API is called by the target. When the ability is started on the target device, this API is called to instruct the application to synchronize the memory data and UI component state, and triggers page restoration after the synchronization is complete. If the continuation logic is not implemented, the ability will be started in common startup mode and the page cannot be restored. -3. Implement the continuation logic in the **onCreate** API. - - The **onCreate** API is called by the **target**. When the ability is started on the target device, this API is called to instruct the application to synchronize the memory data and UI component status, and triggers page restoration after the synchronization is complete. If the continuation logic is not implemented, the ability will be started in common startup mode and the page cannot be restored. - - - The target device determines whether the startup is **LaunchReason.CONTINUATION** based on **launchReason** in **onCreate**. - - - - After data restore is complete, call **restoreWindowStage** to trigger page restoration. - - - * Example + The target device determines whether the startup is **LaunchReason.CONTINUATION** based on **launchReason** in **onCreate()**. + + After data restore is complete, call **restoreWindowStage** to trigger page restoration. + + Example ```javascript onCreate(want, launchParam) { Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) globalThis.abilityWant = want; if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { - let input = want.parameters.input // get user data from want params + let input = want.parameters.input // Obtain user data from want params. AppStorage.SetOrCreate('ContinueInput', input) Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`) @@ -159,71 +163,68 @@ The following table lists the APIs used for ability continuation. For details ab ### Data Continuation -1. Use distributed objects. - - Distributed data objects allow cross-device data synchronization like local variables. For two devices that form a Super Device, when data in the distributed data object of an application is added, deleted, or modified on a device, the data for the same application is also updated on the other device. Both devices can listen for the data changes and online and offline states of the other. For details, see [Distributed Data Object Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/database/database-distributedobject-guidelines.md). - - In the ability continuation scenario, the distributed data object is used to synchronize the memory data from the local device to the target device. - - - In **onContinue**, the initiator saves the data to be continued to the distributed object, sets the session ID, and sends the session ID to the target device through **wantParam**. - - ```javascript - import Ability from '@ohos.application.Ability'; - import distributedObject from '@ohos.data.distributedDataObject'; - - var g_object = distributedObject.createDistributedObject({name:undefined}); - - export default class MainAbility extends Ability { - contentStorage : ContentStorage - sessionId : string; - - onContinue(wantParam : {[key: string]: any}) { - Logger.info("onContinue using distributedObject") - this.sessionId = distributedObject.genSessionId(); - // Set the session ID for the distributed data object. - g_object.setSessionId(this.sessionId); - g_object.name = "Amy"; - // Set the session ID into the want parameter. - wantParam["session"] = this.sessionId; - return AbilityConstant.OnContinueResult.AGREE - } - - ``` - - - The target device obtains the session ID from **onCreate**, creates a distributed object, and associates the distributed object with the session ID. In this way, the distributed object can be synchronized. Before calling **restoreWindowStage**, ensure that all distributed objects required for continuation have been associated for correct data retrieval. - - ```javascript - import Ability from '@ohos.application.Ability'; - import distributedObject from '@ohos.data.distributedDataObject'; - - var g_object = distributedObject.createDistributedObject({name:undefined}); - - export default class MainAbility extends Ability { - contentStorage : ContentStorage - sessionId : string; - - statusCallback(sessionId, networkid, status) { - Logger.info(`continuation object status change, sessionId: ${sessionId}, status: ${status}, g_object.name: ${g_object.name}`) - } - - onCreate(want, launchParam) { - Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) - if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { - // Obtain the session ID of the distributed data object from the want parameter. - this.sessionId = want.parameters.session - Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`) - - g_object.on("status", this.statusCallback); - // Set the session ID for data synchronization. - g_object.setSessionId(this.sessionId); - - this.contentStorage = new ContentStorage(); - this.context.restoreWindowStage(this.contentStorage); - } - } +Use distributed objects. + +Distributed objects allow cross-device data synchronization like local variables. For two devices that form a Super Device, when data in the distributed data object of an application is added, deleted, or modified on a device, the data for the same application is also updated on the other device. Both devices can listen for the data changes and online and offline states of the other. For details, see [Distributed Data Object Development](../database/database-distributedobject-guidelines.md). + +In the ability continuation scenario, the distributed data object is used to synchronize the memory data from the local device to the target device. + +- In **onContinue()**, the initiator saves the data to be continued to the distributed object, sets the session ID, and sends the session ID to the target device through **wantParam**. + + ```javascript + import Ability from '@ohos.application.Ability'; + import distributedObject from '@ohos.data.distributedDataObject'; + + var g_object = distributedObject.createDistributedObject({name:undefined}); + + export default class MainAbility extends Ability { + contentStorage : ContentStorage + sessionId : string; + + onContinue(wantParam : {[key: string]: any}) { + Logger.info("onContinue using distributedObject") + this.sessionId = distributedObject.genSessionId(); + // Set the session ID for the distributed data object. + g_object.setSessionId(this.sessionId); + g_object.name = "Amy"; + // Set the session ID into the want parameter. + wantParam["session"] = this.sessionId; + return AbilityConstant.OnContinueResult.AGREE } - ``` - - - -For details about the complete example, see the sample. + ``` + + + +- The target device obtains the session ID from **onCreate()**, creates a distributed object, and associates the distributed object with the session ID. In this way, the distributed object can be synchronized. Before calling **restoreWindowStage**, ensure that all distributed objects required for continuation have been associated. + + ```javascript + import Ability from '@ohos.application.Ability'; + import distributedObject from '@ohos.data.distributedDataObject'; + + var g_object = distributedObject.createDistributedObject({name:undefined}); + + export default class MainAbility extends Ability { + contentStorage : ContentStorage + sessionId : string; + + statusCallback(sessionId, networkid, status) { + Logger.info(`continuation object status change, sessionId: ${sessionId}, status: ${status}, g_object.name: ${g_object.name}`) + } + + onCreate(want, launchParam) { + Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) + if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { + // Obtain the session ID of the distributed data object from the want parameter. + this.sessionId = want.parameters.session + Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`) + + g_object.on("status", this.statusCallback); + // Set the session ID for data synchronization. + g_object.setSessionId(this.sessionId); + + this.contentStorage = new ContentStorage(); + this.context.restoreWindowStage(this.contentStorage); + } + } + } + ``` diff --git a/en/application-dev/ability/stage-ability.md b/en/application-dev/ability/stage-ability.md index 6d436a445638346dcdc616ac967e0b6d10a00b81..91e7d1132a048a74ab168208d5f2212683350b78 100644 --- a/en/application-dev/ability/stage-ability.md +++ b/en/application-dev/ability/stage-ability.md @@ -1,18 +1,14 @@ # Ability Development ## When to Use -The stage model is an application development model introduced in API version 9. For details about this model, see [Stage Model Overview](stage-brief.md). To develop an ability based on the stage model, you must implement the following logic: -- Create Page abilities for an application that needs to be browsed on the screen and supports man-machine interaction, such as video playback and news browsing. -- Obtain ability configuration information, such as **ApplicationInfo**, **AbilityInfo**, and **HapModuleInfo**. -- Start an ability, start an ability with start options, start an ability with the returned result, or start an ability with an account ID. -- Request certain permissions from end users. -- Notify the ability stage and ability of environment configuration changes. -- Call common components. For details, see [Call Development](stage-call.md). -- Connect to and disconnect from the Service Extension ability. For details, see [Service Extension Ability Development](stage-serviceextension.md). -- Continue the application on another device. For details, see [Ability Continuation Development](stage-ability-continuation.md). +Unlike the FA model, the [stage model](stage-brief.md) requires you to declare the application package structure in the `module.json` and `app.json` files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To develop abilities based on the stage model, implement the following logic: +- Create abilities for an application that involves screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes. +- Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page. +- Call abilities. For details, see [Call Development](stage-call.md). +- Connect to and disconnect from a Service Extension ability. For details, see [Service Extension Ability Development](stage-serviceextension.md). +- Continue the ability on another device. For details, see [Ability Continuation Development](stage-ability-continuation.md). ### Launch Type -The ability supports three launch types: singleton, multi-instance, and instance-specific. -The **launchType** item in the **module.json** file is used to specify the launch type. +The ability supports three launch types: singleton, multi-instance, and instance-specific. Each launch type, specified by `launchType` in the `module.json` file, specifies the action that can be performed when the ability is started. | Launch Type | Description |Description | | ----------- | ------- |---------------- | @@ -20,56 +16,49 @@ The **launchType** item in the **module.json** file is used to specify the launc | singleton | Singleton | Only one instance exists in the system. If an instance already exists when an ability is started, that instance is reused.| | specified | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.| -By default, **singleton** is used. - -## Available APIs -The table below describes the APIs provided by the **AbilityStage** class, which has the **context** attribute. For details about the APIs, see [AbilityStage](../reference/apis/js-apis-application-abilitystage.md). +By default, the singleton mode is used. The following is an example of the `module.json` file: +```json +{ + "module": { + "abilities": [ + { + "launchType": "singleton", + } + ] + } +} +``` +## Creating an Ability +### Available APIs +The table below describes the APIs provided by the `AbilityStage` class, which has the `context` attribute. For details about the APIs, see [AbilityStage](../reference/apis/js-apis-application-abilitystage.md). **Table 1** AbilityStage APIs |API|Description| |:------|:------| -|void onCreate()|Called when an ability stage is created.| -|string onAcceptWant(want: Want)|Called when a specified ability is started.| -|void onConfigurationUpdated(config: Configuration)|Called when the global configuration is updated.| +|onCreate(): void|Called when an ability stage is created.| +|onAcceptWant(want: Want): string|Called when a specified ability is started.| +|onConfigurationUpdated(config: Configuration): void|Called when the global configuration is updated.| -The table below describes the APIs provided by the **Ability** class. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md). +The table below describes the APIs provided by the `Ability` class. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md). **Table 2** Ability APIs |API|Description| |:------|:------| -|void onCreate(want: Want, param: AbilityConstant.LaunchParam)|Called when an ability is created.| -|void onDestroy()|Called when the ability is destroyed.| -|void onWindowStageCreate(windowStage: window.WindowStage)|Called when a **WindowStage** is created for the ability. You can use the **window.WindowStage** APIs to implement operations such as page loading.| -|void onWindowStageDestroy()|Called when the **WindowStage** is destroyed for the ability.| -|void onForeground()|Called when the ability is running in the foreground.| -|void onBackground()|Called when the ability is switched to the background.| -|void onNewWant(want: Want)|Called when the ability startup mode is set to singleton.| -|void onConfigurationUpdated(config: Configuration)|Called when the configuration of the environment where the ability is running is updated.| - -The **Ability** class has the **context** attribute, which belongs to the **AbilityContext** class. The **AbilityContext** class has attributes such as **abilityInfo** and **currentHapModuleInfo**. For details about the APIs, see [AbilityContext](../reference/apis/js-apis-ability-context.md). - -**Table 3** AbilityContext APIs -|API|Description| -|:------|:------| -|void startAbility(want: Want, callback: AsyncCallback)|Starts an ability.| -|void startAbility(want: Want, options: StartOptions, callback: AsyncCallback)|Starts an ability with start options.| -|void startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback)|Starts an ability with the account ID.| -|void startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback)|Starts an ability with the account ID and start options.| -|void startAbilityForResult(want: Want, callback: AsyncCallback)|Starts an ability with the returned result.| -|void startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback)|Starts an ability with the returned result and start options.| -|void startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback)|Starts an ability with the returned result and account ID.| -|void startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback)|Starts an ability with the returned result, account ID, and start options.| -|void terminateSelf(callback: AsyncCallback)|Destroys the Page ability.| -|void terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback)|Destroys the Page ability with the returned result.| - -## How to Develop -### Creating Page Abilities for an Application -To create Page abilities for an application on the stage model, you must implement the **AbilityStage** class and ability lifecycle callbacks, and use the **Window** APIs to set the pages. The sample code is as follows: -1. Import the **AbilityStage** module. +|onCreate(want: Want, param: AbilityConstant.LaunchParam): void|Called when an ability is created.| +|onDestroy(): void|Called when the ability is destroyed.| +|onWindowStageCreate(windowStage: window.WindowStage): void|Called when a `WindowStage` is created for the ability. You can use the `window.WindowStage` APIs to implement operations such as page loading.| +|onWindowStageDestroy(): void|Called when the `WindowStage` is destroyed for the ability.| +|onForeground(): void|Called when the ability is switched to the foreground.| +|onBackground(): void|Called when the ability is switched to the background.| +|onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void|Called when the ability launch type is set to `singleton`.| +|onConfigurationUpdated(config: Configuration): void|Called when the configuration of the environment where the ability is running is updated.| +### Implementing AbilityStage and Ability Lifecycle Callbacks +To create Page abilities for an application in the stage model, you must implement the `AbilityStage` class and ability lifecycle callbacks, and use the `Window` APIs to set the pages. The sample code is as follows: +1. Import the `AbilityStage` module. ``` import AbilityStage from "@ohos.application.AbilityStage" ``` -2. Implement the **AbilityStage** class. +2. Implement the `AbilityStage` class. ```ts export default class MyAbilityStage extends AbilityStage { onCreate() { @@ -77,13 +66,13 @@ To create Page abilities for an application on the stage model, you must impleme } } ``` -3. Import the **Ability** module. +3. Import the `Ability` module. ```js import Ability from '@ohos.application.Ability' ``` -4. Implement the lifecycle callbacks of the **Ability** class. +4. Implement the lifecycle callbacks of the `Ability` class. - In the **onWindowStageCreate(windowStage)** API, use **loadContent** to set the pages to be loaded by the application. For details about how to use the **Window** APIs, see [Window Development](../windowmanager/window-guidelines.md). + In the `onWindowStageCreate(windowStage)` API, use `loadContent` to set the application page to be loaded. For details about how to use the `Window` APIs, see [Window Development](../windowmanager/window-guidelines.md). ```ts export default class MainAbility extends Ability { onCreate(want, launchParam) { @@ -100,7 +89,7 @@ To create Page abilities for an application on the stage model, you must impleme 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)) + console.error("MainAbility load content failed with error: " + JSON.stringify(error)) }) } @@ -117,8 +106,8 @@ To create Page abilities for an application on the stage model, you must impleme } } ``` -### Obtaining AbilityStage and Ability Configuration Information -Both the **AbilityStage** and **Ability** classes have the **context** attribute. An application can obtain the context of the **Ability** instance through **this.context** to obtain detailed configuration information. The following example shows how the ability stage obtains the bundle code directory, HAP file name, ability name, and system language through the **context** attribute. The sample code is as follows: +### Obtaining AbilityStage and Ability Configurations +Both the `AbilityStage` and `Ability` classes have the `context` attribute. An application can obtain the context of an `Ability` instance through `this.context` to obtain the configuration details. The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `AbilityStage` class. The sample code is as follows: ```ts import AbilityStage from "@ohos.application.AbilityStage" export default class MyAbilityStage extends AbilityStage { @@ -137,7 +126,7 @@ export default class MyAbilityStage extends AbilityStage { } ``` -The following example shows how the ability obtains the bundle code directory, HAP file name, ability name, and system language through the **context** attribute. The sample code is as follows: +The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `Ability` class. The sample code is as follows: ```ts import Ability from '@ohos.application.Ability' export default class MainAbility extends Ability { @@ -155,9 +144,82 @@ export default class MainAbility extends Ability { } } ``` +### Requesting Permissions +If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the permission from consumers. During application development, you need to specify the involved sensitive permissions, declare the required permissions in `module.json`, and use the `requestPermissionsFromUser` API to request the permission from consumers in the form of a dialog box. The following uses the permissions for calendar access as an example. + +Declare the required permissions in the `module.json` file. +```json +"requestPermissions": [ + { + "name": "ohos.permission.READ_CALENDAR" + } +] +``` +Request the permissions from consumers in the form of a dialog box: +```ts +let context = this.context +let permissions: Array = ['ohos.permission.READ_CALENDAR'] +context.requestPermissionsFromUser(permissions).then((data) => { + console.log("Succeed to request permission from user with data: " + JSON.stringify(data)) +}).catch((error) => { + console.log("Failed to request permission from user with error: " + JSON.stringify(error)) +}) +``` +### Notifying of Environment Changes +Environment changes include changes of global configurations and ability configurations. Currently, the global configurations include the system language and color mode. The change of global configurations is generally triggered by the configuration item in **Settings** or the icon in **Control Panel**. The ability configuration is specific to a single `Ability` instance, including the display ID, screen resolution, and screen orientation. The configuration is related to the display where the ability is located, and the change is generally triggered by the window. For details on the configuration, see [Configuration](../reference/apis/js-apis-configuration.md). + +For an application in the stage model, when the configuration changes, its abilities are not restarted, but the `onConfigurationUpdated(config: Configuration)` callback is triggered. If the application needs to perform processing based on the change, you can overwrite `onConfigurationUpdated`. Note that the `Configuration` object in the callback contains all the configurations of the current ability, not only the changed configurations. + +The following example shows the implement of the `onConfigurationUpdated` callback in the `AbilityStage` class. The callback is triggered when the system language and color mode are changed. +```ts +import Ability from '@ohos.application.Ability' +import ConfigurationConstant from '@ohos.application.ConfigurationConstant' + +export default class MyAbilityStage extends AbilityStage { + onConfigurationUpdated(config) { + if (config.colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK) { + console.log('colorMode changed to dark') + } + } +} +``` + +The following example shows the implement of the `onConfigurationUpdated` callback in the `Ability` class. The callback is triggered when the system language, color mode, or display parameters (such as the direction and density) change. +```ts +import Ability from '@ohos.application.Ability' +import ConfigurationConstant from '@ohos.application.ConfigurationConstant' + +export default class MainAbility extends Ability { + direction : number; + + onCreate(want, launchParam) { + this.direction = this.context.config.direction + } + + onConfigurationUpdated(config) { + if (this.direction !== config.direction) { + console.log(`direction changed to ${config.direction}`) + } + } +} +``` +## Starting an Ability +### Available APIs +The `Ability` class has the `context` attribute, which belongs to the `AbilityContext` class. The `AbilityContext` class has the `abilityInfo`, `currentHapModuleInfo`, and other attributes and the APIs used for starting abilities. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md). -### Starting an Ability -An application can obtain the context of an **Ability** instance through **this.context** and then use the **StartAbility** API in the **AbilityContext** class to start the ability. The ability can be started by specifying **Want**, **StartOptions**, and **accountId**, and the operation result can be returned using a callback or **Promise** instance. The sample code is as follows: +**Table 3** AbilityContext APIs +|API|Description| +|:------|:------| +|startAbility(want: Want, callback: AsyncCallback\): void|Starts an ability.| +|startAbility(want: Want, options?: StartOptions): Promise\|Starts an ability.| +|startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void|Starts an ability with the account ID.| +|startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\|Starts an ability with the account ID.| +|startAbilityForResult(want: Want, callback: AsyncCallback\): void|Starts an ability with the returned result.| +|startAbilityForResult(want: Want, options?: StartOptions): Promise\|Starts an ability with the returned result.| +|startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void|Starts an ability with the execution result and account ID.| +|startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\|Starts an ability with the execution result and account ID.| +### Starting an Ability on the Same Device +An application can obtain the context of an `Ability` instance through `this.context` and then use the `startAbility` API in the `AbilityContext` class to start the ability. The ability can be started by specifying `Want`, `StartOptions`, and `accountId`, and the operation result can be returned using a callback or `Promise` instance. The sample code is as follows: ```ts let context = this.context var want = { @@ -165,20 +227,17 @@ var want = { "bundleName": "com.example.MyApplication", "abilityName": "MainAbility" }; -var options = { - windowMode: 0, - displayId: 2 -}; -context.startAbility(want, options).then((data) => { +context.startAbility(want).then((data) => { console.log("Succeed to start ability with data: " + JSON.stringify(data)) }).catch((error) => { console.error("Failed to start ability with error: "+ JSON.stringify(error)) }) ``` -### Starting an Ability on a Remote Device (Available only to System Applications) ->Note: The **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. Therefore, cross-device ability startup applies only to system applications. +### Starting an Ability on a Remote Device +This feature applies only to system applications, since the `getTrustedDeviceListSync` API of the `DeviceManager` class is open only to system applications. In the cross-device scenario, you must specify the ID of the remote device. The sample code is as follows: + ```ts let context = this.context var want = { @@ -189,10 +248,10 @@ var want = { context.startAbility(want).then((data) => { console.log("Succeed to start remote ability with data: " + JSON.stringify(data)) }).catch((error) => { - console.error("Failed to start remote ability with error: "+ JSON.stringify(error)) + console.error("Failed to start remote ability with error: " + JSON.stringify(error)) }) ``` -Obtain the ID of a specified device from **DeviceManager**. The sample code is as follows: +Obtain the ID of a specified device from `DeviceManager`. The sample code is as follows: ```ts import deviceManager from '@ohos.distributedHardware.deviceManager'; function getRemoteDeviceId() { @@ -209,68 +268,57 @@ function getRemoteDeviceId() { } } ``` +Request the permission `ohos.permission.DISTRIBUTED_DATASYNC ` from consumers. This permission is used for data synchronization. For details about the sample code for requesting the permission, see [Requesting Permissions](##requesting-permissions). +### Starting an Ability with the Specified Page +If the launch type of an ability is set to `singleton` and the ability has been started, the `onNewWant` callback is triggered when the ability is started again. You can pass start options through the `want`. For example, to start an ability with the specified page, use the `uri` or `parameters` parameter in the `want` to pass the page information. Currently, the ability in the stage model cannot directly use the `router` capability. You must pass the start options to the custom component and invoke the `router` method to display the specified page during the custom component lifecycle management. The sample code is as follows: -### Requesting Permissions -If an application requires certain permissions, such as storage, location information, and log access, the application must request the permissions from end users. After determining the required permissions, add the permissions in the **module.json** file and use **requestPermissionsFromUser** to request the permissions from end users in the form of a dialog box. The following uses the permissions for calendar access as an example. -Modify the **module.json** file as follows: -```json -"requestPermissions": [ - { - "name": "ohos.permission.READ_CALENDAR" - } -] -``` -Request the permissions from end users in the form of a dialog box: +When using `startAbility` to start an ability again, use the `uri` parameter in the `want` to pass the page information. ```ts -let context = this.context -let permissions: Array = ['ohos.permission.READ_CALENDAR'] -context.requestPermissionsFromUser(permissions).then((data) => { - console.log("Succeed to request permission from user with data: "+ JSON.stringify(data)) -}).catch((error) => { - console.log("Failed to request permission from user with error: "+ JSON.stringify(error)) -}) -``` -In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code is as follows: -```ts -let context = this.context -let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] -context.requestPermissionsFromUser(permissions).then((data) => { - console.log("Succeed to request permission from user with data: "+ JSON.stringify(data)) -}).catch((error) => { - console.log("Failed to request permission from user with error: "+ JSON.stringify(error)) -}) +async function reStartAbility() { + try { + await this.context.startAbility({ + bundleName: "com.sample.MyApplication", + abilityName: "MainAbility", + uri: "pages/second" + }) + console.log('start ability succeed') + } catch (error) { + console.error(`start ability failed with ${error.code}`) + } +} ``` -### Notifying of Environment Configuration Changes -When the global configuration, for example, system language and color mode, changes, the **onConfigurationUpdated** API is called to notify the ability stage and ability. System applications can update the system language and color mode through the **updateConfiguration** API. The following example shows the implement of the **onConfigurationUpdated** callback in the **AbilityStage** class. The callback is triggered when the system language and color mode change. The sample code is as follows: +Obtain the `want` parameter that contains the page information from the `onNewWant` callback of the ability. ```ts import Ability from '@ohos.application.Ability' -import ConfigurationConstant from '@ohos.application.ConfigurationConstant' -export default class MyAbilityStage extends AbilityStage { - onConfigurationUpdated(config) { - console.log("MyAbilityStage onConfigurationUpdated") - console.log("MyAbilityStage config language" + config.language) - console.log("MyAbilityStage config colorMode" + config.colorMode) - } + +export default class MainAbility extends Ability { + onNewWant(want, launchParams) { + globalThis.newWant = want + } } ``` -The following example shows the implement of the **onConfigurationUpdated** callback in the **Ability** class. The callback is triggered when the system language, color mode, and display parameters (such as the direction and density) change. The sample code is as follows: +Obtain the `want` parameter that contains the page information from the custom component and process the route based on the URI. ```ts -import Ability from '@ohos.application.Ability' -import ConfigurationConstant from '@ohos.application.ConfigurationConstant' -export default class MainAbility extends Ability { { - onConfigurationUpdated(config) { - console.log("MainAbility onConfigurationUpdated") - console.log("MainAbility config language" + config.language) - console.log("MainAbility config colorMode" + config.colorMode) - console.log("MainAbility config direction" + config.direction) - console.log("MainAbility config screenDensity" + config.screenDensity) - console.log("MainAbility config displayId" + config.displayId) +import router from '@system.router' + +@Entry +@Component +struct Index { + newWant = undefined + + onPageShow() { + console.info('Index onPageShow') + let newWant = globalThis.newWant + if (newWant.hasOwnProperty("uri")) { + router.push({ uri: newWant.uri }); + globalThis.newWant = undefined } + } } ``` ## Samples The following sample is provided to help you better understand how to develop an ability on the stage model: -- [`StageCallAbility`: Stage Ability Creation and Usage (eTS) (API9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility) +- [`StageCallAbility`: Stage Call Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility) diff --git a/en/application-dev/ability/stage-call.md b/en/application-dev/ability/stage-call.md index 36efd3076702ef26c37cd304794ea2caf36e053d..e402454ddf6afd1b1aab71601e52b19d8010b425 100644 --- a/en/application-dev/ability/stage-call.md +++ b/en/application-dev/ability/stage-call.md @@ -18,11 +18,11 @@ The table below describes the ability call APIs. For details, see [Ability](../r **Table 1** Ability call APIs |API|Description| |:------|:------| -|startAbilityByCall(want: Want): Promise|Obtains the caller interface of the specified ability and, if the specified ability is not running, starts the ability in the background.| +|startAbilityByCall(want: Want): Promise\|Obtains the caller interface of the specified ability and, if the specified ability is not running, starts the ability in the background.| |on(method: string, callback: CaleeCallBack): void|Callback invoked when the callee registers a method.| |off(method: string): void|Callback invoked when the callee deregisters a method.| -|call(method: string, data: rpc.Sequenceable): Promise|Sends agreed sequenceable data to the callee.| -|callWithResult(method: string, data: rpc.Sequenceable): Promise|Sends agreed sequenceable data to the callee and returns the agreed sequenceable data.| +|call(method: string, data: rpc.Sequenceable): Promise\|Sends agreed sequenceable data to the callee.| +|callWithResult(method: string, data: rpc.Sequenceable): Promise\|Sends agreed sequenceable data to the callee and returns the agreed sequenceable data.| |release(): void|Releases the caller interface.| |onRelease(callback: OnReleaseCallBack): void|Registers a callback that is invoked when the caller is disconnected.| @@ -83,7 +83,7 @@ export default class MySequenceable { ``` 4. Implement **Callee.on** and **Callee.off**. - The time to register a listener for the callee depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **CalleeSortMethod** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code snippet is as follows: + The time to register a listener for the callee depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code snippet is as follows: ```ts const TAG: string = '[CalleeAbility]' const MSG_SEND_METHOD: string = 'CallSendMsg' @@ -148,7 +148,7 @@ async onButtonGetCaller() { console.error(TAG + 'get caller failed with ' + error) }) ``` -In the cross-device scenario, you need to specify the ID of the peer device. The sample code snippet is as follows: + In the cross-device scenario, you need to specify the ID of the peer device. The sample code snippet is as follows: ```ts let TAG = '[MainAbility] ' var caller = undefined @@ -172,7 +172,7 @@ context.startAbilityByCall({ console.error(TAG + 'get remote caller failed with ' + error) }) ``` -Obtain the ID of the peer device from **DeviceManager**. Note that the **getTrustedDeviceListSync** API is open only to system applications. The sample code snippet is as follows: + Obtain the ID of the peer device from **DeviceManager**. Note that the **getTrustedDeviceListSync** API is open only to system applications. The sample code snippet is as follows: ```ts import deviceManager from '@ohos.distributedHardware.deviceManager'; var dmClass; @@ -190,7 +190,7 @@ function getRemoteDeviceId() { } } ``` -In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code snippet is as follows: + In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code snippet is as follows: ```ts let context = this.context let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] @@ -215,7 +215,7 @@ async onButtonCall() { } ``` -In the following, **CallWithResult** is used to send data **originMsg** to the callee and assign the data processed by the **CallSendMsg** method to **backMsg**. The sample code snippet is as follows: + In the following, **CallWithResult** is used to send data **originMsg** to the callee and assign the data processed by the **CallSendMsg** method to **backMsg**. The sample code snippet is as follows: ```ts const MSG_SEND_METHOD: string = 'CallSendMsg' originMsg: string = '' diff --git a/en/application-dev/ability/stage-formextension.md b/en/application-dev/ability/stage-formextension.md index 21120b62239b70c166fd90d20839e1acea2486f6..e1d3604c566b217a7b4f9f2c880faf5d4c71cf47 100644 --- a/en/application-dev/ability/stage-formextension.md +++ b/en/application-dev/ability/stage-formextension.md @@ -4,18 +4,15 @@ A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application. -A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive features such as opening a UI page or sending a message. The widget host is responsible for displaying the service widget. +A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message. Basic concepts: -- Widget provider
- The widget provider is an atomic service that provides the content to be displayed. It controls the display content, component layout, and component click events of a widget. -- Widget host
- The widget host is an application that displays the widget content and controls the position where the widget is displayed in the host application. -- Widget Manager
- The Widget Manager is a resident agent that manages widgets added to the system and provides functions such as periodic widget update. +- Widget provider: an atomic service that controls what and how content is displayed in a widget and interacts with users. +- Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application. +- Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated. You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager. @@ -24,16 +21,16 @@ The widget provider controls the widget content to display, component layout, an ## When to Use -Stage ability development refers to the development conducted by the widget provider based on the [stage model](stage-brief.md). As a widget provider, you need to carry out the following operations: +Stage widget development refers to the development conducted by the widget provider based on the [stage model](stage-brief.md). As a widget provider, you need to carry out the following operations: -- Develop the lifecycle callback functions in **FormExtension**. -- Create a **FormBindingData** object. +- Develop the lifecycle callbacks in **FormExtension**. +- Create a **FormBindingData** instance. - Update a widget through **FormProvider**. - Develop the widget UI page. ## Available APIs -The **FormExtension** class has the **context** attribute. For details on the APIs provided by the **FormExtension** class, see [FormExtension](../reference/apis/js-apis-formextension.md). +The **FormExtension** class has the following APIs. For details, see [FormExtension](../reference/apis/js-apis-formextension.md). **Table 1** FormExtension APIs @@ -42,19 +39,19 @@ The **FormExtension** class has the **context** attribute. For details on the AP | onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a **Form** instance (widget) has been created. | | onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| | onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. | -| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change of widget visibility. | -| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process the widget event. | +| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility. | +| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event. | | onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. | -| onConfigurationUpdated(config: Configuration): void; | Called when the configuration of the environment where the ability is running is updated. | +| onConfigurationUpdated(config: Configuration): void; | Called when the configuration of the environment where the widget is running is updated. | -The **context** attribute of the **FormExtension** class inherits from the **FormExtensionContext** class. For details about the APIs provided by the **FormExtensionContext** class, see [FormExtensionContext](../reference/apis/js-apis-formextensioncontext.md). +The **FormExtension** class also has a member context, that is, the **FormExtensionContext** class. For details, see [FormExtensionContext](../reference/apis/js-apis-formextensioncontext.md). **Table 2** FormExtensionContext APIs | API | Description | | :----------------------------------------------------------- | :------------------------ | -| updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void | Updates a widget. This method uses a callback to return the result. | -| updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise\ | Updates a widget. This method uses a promise to return the result.| +| updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void | Updates a widget. This API uses an asynchronous callback to return the result. | +| updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise\ | Updates a widget. This API uses a promise to return the result.| For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md). @@ -69,9 +66,9 @@ For details about the **FormProvider** APIs, see [FormProvider](../reference/api ## How to Develop -### Creating a Form Extension +### Creating a FormExtension Instance -To create a widget in the stage model, you need to implement the lifecycle callback functions of **FormExtension**. The sample code is as follows: +To create a widget in the stage model, implement the lifecycle callbacks of **FormExtension**. The sample code is as follows: 1. Import the required modules. @@ -82,13 +79,13 @@ To create a widget in the stage model, you need to implement the lifecycle callb import formProvider from '@ohos.application.formProvider' ``` -2. Implement the lifecycle callback functions of **FormExtension**. +2. Implement the lifecycle callbacks of **FormExtension**. ```javascript export default class FormAbility extends FormExtension { onCreate(want) { console.log('FormAbility onCreate'); - // Persistently store widget information for subsequent use, such as widget instance retrieval and update. + // Persistently store widget information for subsequent use, such as during widget instance retrieval or update. let obj = { "title": "titleOnCreate", "detail": "detailOnCreate" @@ -101,7 +98,7 @@ To create a widget in the stage model, you need to implement the lifecycle callb console.log('FormAbility onCastToNormal'); } onUpdate(formId) { - // To support scheduled update, periodic update, or update requested by the widget host for a widget, override this method for data update. + // To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update. console.log('FormAbility onUpdate'); let obj = { "title": "titleOnUpdate", @@ -130,24 +127,22 @@ To create a widget in the stage model, you need to implement the lifecycle callb } ``` -### Configuring config.json for the Form Ability - -Configure the **module.json** file for the **Form** ability. +### Configuring the Widget Configuration File -- The internal field structure of the **extensionAbility** module is described as follows: +- Configure Extension ability information under **extensionAbilities** in the **module.json5** file. The internal field structure is described as follows: | Field | Description | Data Type | Default | | ----------- | ------------------------------------------------------------ | ---------- | -------------------- | - | name | Name of an extension ability. | String | No | - | srcEntrance | JS code path of the extension ability. | String | No | - | description | Description of the extension ability. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty)| - | icon | Index of the extension ability icon file. | String | Yes (initial value: left empty)| - | label | Descriptive information about the extension ability presented externally. The value can be a string or a resource index to the description.| String | Yes (initial value: left empty)| - | type | Type of the extension ability. The value can be **form** or **service**. | String | No | + | name | Name of the Extension ability. This field must be specified. | String | No | + | srcEntrance | Path of the Extension ability lifecycle code. This field must be specified.| String | No | + | description | Description of the Extension ability. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty)| + | icon | Index of the Extension ability icon file. | String | Yes (initial value: left empty)| + | label | Descriptive information about the Extension ability presented externally. The value can be a string or a resource index to the description.| String | Yes (initial value: left empty)| + | type | Type of the Extension ability. In the current development scenario, set this field to **form**.| String | No | | permissions | Permissions required for abilities of another application to call the current ability. | String array| Yes (initial value: left empty)| - | metadata | Metadata of the extension ability. It describes the configuration information of the extension ability.| Object | Yes (initial value: left empty) | + | metadata | Metadata (configuration information) of the Extension ability.| Object | Yes (initial value: left empty) | - For a Form Extension ability, set **type** to **form** and **metadata** to the widget details. + For a Form Extension ability, you must specify **metadata**. Specifically, set **name** to **ohos.extension.form** (fixed), and set **resource** to the index of the widget configuration information. A configuration example is as follows: @@ -165,25 +160,25 @@ Configure the **module.json** file for the **Form** ability. }] ``` -- Configure the widget profile module. In the metadata of the Form Extension ability, the resource file path specified by **ohos.extension.form** must be used. For example, **$profile:form_config** means that **form_config.json** in the **resources/base/profile/** directory of the development view is used as the widget profile. +- Configure the widget configuration information. **resource** in **metadata** specifies the index of the widget configuration information. For example, **$profile:form_config** means that **form_config.json** in the **resources/base/profile/** directory of the development view is used as the widget profile configuration file. The internal field structure is described as follows: | Field | Description | Data Type | Default | | ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ | - | name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | + | name | Class name of a widget. The value is a string with a maximum of 127 bytes. | String | No | | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | | src | Full path of the UI code corresponding to the widget. | String | No | | window | Window-related configurations. | Object | Yes | | isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | | colorMode | Color mode of the widget. Available values are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| - | supportDimensions | Grid styles supported by the widget. Available values are as follows:
1 * 2: indicates a grid with one row and two columns.
2 * 2: indicates a grid with two rows and two columns.
2 * 4: indicates a grid with two rows and four columns.
4 * 4: indicates a grid with four rows and four columns.| String array| No | + | supportDimensions | Grid styles supported by the widget. Available values are as follows:
**1 * 2**: indicates a grid with one row and two columns.
**2 * 2**: indicates a grid with two rows and two columns.
**2 * 4**: indicates a grid with two rows and four columns.
**4 * 4**: indicates a grid with four rows and four columns.| String array| No | | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | - | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | + | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | | formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | - | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | + | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | | metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) | A configuration example is as follows: @@ -211,9 +206,9 @@ Configure the **module.json** file for the **Form** ability. ``` -### Widget Data Persistence +### Persistently Storing Widget Data -Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget. +Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting the widget. ```javascript onCreate(want) { @@ -222,7 +217,8 @@ Mostly, the widget provider is started only when it needs to obtain information let formId = want.parameters["ohos.extra.param.key.form_identity"]; let formName = want.parameters["ohos.extra.param.key.form_name"]; let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; - // Persistently store widget information for subsequent use, such as widget instance retrieval and update. + // Persistently store widget data for subsequent use, such as widget instance retrieval and update. + // The storeFormInfo API is not implemented here. For details about the implementation, see "Samples" below. storeFormInfo(formId, formName, tempFlag, want); let obj = { @@ -238,9 +234,11 @@ You should override **onDestroy** to delete widget data. ```javascript onDestroy(formId) { - // Delete widget data. - deleteFormInfo(formId); console.log('FormAbility onDestroy'); + + // You need to implement the code for deleting the persistent widget data. + // The deleteFormInfo API is not implemented here. For details about the implementation, see "Samples" below. + deleteFormInfo(formId); } ``` @@ -248,11 +246,11 @@ For details about the persistence method, see [Lightweight Data Store Developmen Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one. -Normal widget: a widget that will be persistently used by the widget host +- Normal widget: a widget that will be persistently used by the widget host -Temporary widget: a widget that is temporarily used by the widget host +- Temporary widget: a widget that is temporarily used by the widget host -Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget host may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets. +Data of a temporary widget is not persistently stored. If it is deleted from the Widget Manager due to exceptions, such as crash of the widget framework, the widget provider will not be notified of which widget is deleted, and still keeps the data. In light of this, the widget provider should implement data clearing. If the widget host successfully converts a temporary widget into a normal one, the widget provider should also process the widget ID and store the data persistently. This prevents the widget provider from deleting the widget data when clearing temporary widgets. ### Developing the Widget UI Page You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. @@ -339,10 +337,7 @@ Now you've got a widget shown below. ![fa-form-example](figures/fa-form-example.png) -## Development Example +## Samples The following sample is provided to help you better understand how to develop a widget on the stage model: - -[FormExtAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/FormExtAbility) - -Users can create, update, and delete widgets on the home screen of their devices or by using their own widget host. This sample also implements widget information persistence by using lightweight data storage. \ No newline at end of file +- [`FormExtAbility`: Stage Model Widget (eTS, JS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormExtAbility) diff --git a/en/application-dev/ability/stage-serviceextension.md b/en/application-dev/ability/stage-serviceextension.md index 4aaaab6c06a9a2c3d5621c4ba02da1749eefeded..90448c52428af38b8128477c24eec4911b88b827 100644 --- a/en/application-dev/ability/stage-serviceextension.md +++ b/en/application-dev/ability/stage-serviceextension.md @@ -1,9 +1,9 @@ # Service Extension Ability Development ## When to Use -**ExtensionAbility** is the base class of the new **Extension** component in the stage model. It is used to process jobs without UIs. The lifecycle of an Extension ability is simple, and it does not involve foreground or background. **ServiceExtensionAbility** is extended from **ExtensionAbility**. +**ExtensionAbility** is the base class of the new Extension component in the stage model. It is used to process missions without UIs. The lifecycle of an Extension ability is simple, and it does not involve foreground or background. **ServiceExtensionAbility** is extended from **ExtensionAbility**. -You can customize a class that inherits from **ServiceExtensionAbility** and override the lifecycle callbacks of **ServiceExtensionAbility** to perform service logic operations during the initialization, connection, and disconnection processes. +You can customize a class that inherits from **ServiceExtensionAbility** and override the lifecycle callbacks in the base class to perform service logic operations during the initialization, connection, and disconnection processes. ## Available APIs @@ -19,7 +19,7 @@ You can customize a class that inherits from **ServiceExtensionAbility** and ove ## Constraints -- Currently, OpenHarmony does not support creation of a **ServiceExtensionAbility** for third-party applications. +- Currently, OpenHarmony does not support creation of a Service Extension ability for third-party applications. ## How to Develop @@ -82,4 +82,5 @@ The following sample is provided to help you better understand how to develop a - [ServiceExtensionAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceExtAbility) -This sample will guide you through creating a Service Extension ability in the **ServiceExtAbility.ts** file in the **ServiceExtensionAbility** directory. \ No newline at end of file +This sample shows how to create a Service Extension ability in the **ServiceExtAbility.ts** file in the **ServiceExtensionAbility** directory. + diff --git a/en/application-dev/ability/wantagent.md b/en/application-dev/ability/wantagent.md index 013c2010966a891debdc080bd6b1390a19f5537d..eacc92936960cca3bd022e6438a63c15a8f2688a 100644 --- a/en/application-dev/ability/wantagent.md +++ b/en/application-dev/ability/wantagent.md @@ -1,73 +1,86 @@ # WantAgent Development +## When to Use +The **WantAgent** class encapsulates want information that specifies a particular action, which can be starting an ability or publishing a common event. You can either call **wantAgent.trigger** to trigger a **WantAgent** directly or add a **WantAgent** to a notification so that it will be triggered when users tap the notification. -### Introduction -The **WantAgent** class encapsulates a **Want** object that specifies a particular action. You can trigger a **WantAgent** by calling **wantAgent.trigger** directly or by adding it to a notification so that it is triggered when a user taps the notification. - -You can use a **WantAgent** in a notification to start an ability or publish a common event. - -### When to Use -Start another ability through a **WantAgent**. - -### Available APIs +## Available APIs | API | Description| | ---------------------------------------------------------------------------------------------- | ----------- | -| wantAgent.getWantAgentInfo(info: WantAgentInfo, callback: AsyncCallback\) | Creates a **WantAgent** object. This API uses an asynchronous callback to return the result.| -| wantAgent.getWantAgent(info: WantAgentInfo): Promise\; | Creates a **WantAgent** object. This API uses a promise to return the result.| -| commonEvent.trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback\) | Triggers a **WantAgent**.| +| getWantAgentInfo(info: WantAgentInfo, callback: AsyncCallback\) | Creates a **WantAgent** object. This API uses an asynchronous callback to return the result.| +| getWantAgent(info: WantAgentInfo): Promise\ | Creates a **WantAgent** object. This API uses a promise to return the result.| +| trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback\) | Triggers a **WantAgent** object.| -### How to Develop +## How to Develop 1. Import the **WantAgent** module. -```javascript -import wantAgent from '@ohos.wantAgent'; -``` + ``` + import wantAgent from '@ohos.wantAgent'; + ``` + +2. Create a **WantAgentInfo** object that will be used for starting an ability. For details about the data types and parameters of **WantAgentInfo**, see [WantAgent](../reference/apis/js-apis-wantAgent.md#wantagentinfo). -2. Create a **WantAgentInfo** object. For details about the data types and parameters of **WantAgentInfo**, see [WantAgent Module](../reference/apis/js-apis-wantAgent.md#wantagentinfo). + ``` + private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations. + + //wantAgentInfo + var wantAgentInfo = { + wants: [ + { + deviceId: "", + bundleName: "com.example.test", + abilityName: "com.example.test.MainAbility", + action: "", + entities: [], + uri: "", + parameters: {} + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG] + } + ``` -```javascript -private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations. +3. Create a **WantAgentInfo** object for publishing a common event. -//wantAgentInfo -var wantAgentInfo = { - wants: [ - { - deviceId: "", - bundleName: "com.example.test", - abilityName: "com.example.test.MainAbility", - action: "", - entities: [], - uri: "", - parameters: {} - } - ], - operationType: OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.CONSTANT_FLAG] -} -``` + ``` + private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations. + + //wantAgentInfo + var wantAgentInfo = { + wants: [ + { + action: "event_name", // Set the action name. + parameters: {} + } + ], + operationType: wantAgent.OperationType.SEND_COMMON_EVENT, + requestCode: 0, + wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG] + } + ``` -3. Create a **WantAgent** object and save the returned **wantAgentObj** for subsequent trigger operations. +4. Create a **WantAgent** object and save the returned **wantAgentObj** for subsequent trigger operations. -```javascript -// Create a WantAgent object. -wantAgent.getWantAgent(wantAgentInfo, (err, wantAgentObj) => { - if (err.code) { - console.error("[WantAgent]getWantAgent err=" + JSON.stringify(err)) - } else { - console.log("[WantAgent]getWantAgent success") - this.wantAgentObj = wantAgentObj - } -}) -``` + ``` + // Create a WantAgent object. + wantAgent.getWantAgent(wantAgentInfo, (err, wantAgentObj) => { + if (err.code) { + console.error("[WantAgent]getWantAgent err=" + JSON.stringify(err)) + } else { + console.log("[WantAgent]getWantAgent success") + this.wantAgentObj = wantAgentObj + } + }) + ``` -4. Trigger the **WantAgent**. +5. Trigger the **WantAgent** object. -``` -// Trigger the WantAgent. -var triggerInfo = { - code:0 -} -wantAgent.trigger(wantAgentObj, triggerInfo, (completeData) => { - console.log("[WantAgent]getWantAgent success, completeData: ", + JSON.stringify(completeData)) -}) -``` \ No newline at end of file + ``` + // Trigger the WantAgent object. + var triggerInfo = { + code:0 + } + wantAgent.trigger(wantAgentObj, triggerInfo, (completeData) => { + console.log("[WantAgent]getWantAgent success, completeData: ", + JSON.stringify(completeData)) + }) + ``` diff --git a/en/application-dev/application-dev-guide-for-gitee.md b/en/application-dev/application-dev-guide-for-gitee.md index f1f397fc5145208733c85a3e711f3cda0337d409..d626a1975edf7c74ab34a45016f1702f1db4226e 100644 --- a/en/application-dev/application-dev-guide-for-gitee.md +++ b/en/application-dev/application-dev-guide-for-gitee.md @@ -54,7 +54,7 @@ They are organized as follows: - [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 (eTS Included) APIs](reference/apis/Readme-EN.md) + - [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) diff --git a/en/application-dev/application-dev-guide.md b/en/application-dev/application-dev-guide.md index 8e47dd69696fd4ec4f6842f9f08826e181805ada..d79d1af7c2e0fd6a2fe6920b6e729957abe0ed4e 100644 --- a/en/application-dev/application-dev-guide.md +++ b/en/application-dev/application-dev-guide.md @@ -36,6 +36,8 @@ Then, equip yourself for developing the key features, with the following guideli - [Device Usage Statistics](device-usage-statistics/device-usage-statistics-overview.md) - [DFX](dfx/hiappevent-overview.md) - [Internationalization](internationalization/international-overview.md) +- [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) +- [Using Native APIs in Application Projects](napi/napi-guidelines.md) ### Tools @@ -51,6 +53,8 @@ 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 (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/js-components-common-attributes.md) -- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/ts-universal-events-click.md) -- [API Reference](reference/apis/js-apis-DataUriUtils.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/background-agent-scheduled-reminder/background-agent-scheduled-reminder-guide.md b/en/application-dev/background-agent-scheduled-reminder/background-agent-scheduled-reminder-guide.md index 99122b53abc4c5d561302c36dc5c9f489924fced..63e42760af0329365bd1a0379a21259dd3502c14 100644 --- a/en/application-dev/background-agent-scheduled-reminder/background-agent-scheduled-reminder-guide.md +++ b/en/application-dev/background-agent-scheduled-reminder/background-agent-scheduled-reminder-guide.md @@ -1,606 +1,214 @@ -# Agent-Powered Scheduled Reminder Development - -## When to Use - -You can set your application to call the **ReminderRequest** class to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background, even when your application is frozen or exits. - -## Available APIs - -**reminderAgent** encapsulates the methods for publishing and canceling reminders. - -**Table 1** Major APIs in reminderAgent - - - - - - - - - - - - - - - - - - - - - - - - - -

API

-

Description

-

function publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void;

-

function publishReminder(reminderReq: ReminderRequest): Promise<number>;

-

Publishes a scheduled reminder.

-

The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system.

-

function cancelReminder(reminderId: number, callback: AsyncCallback<void>): void;

-

function cancelReminder(reminderId: number): Promise<void>;

-

Cancels a specified reminder. (The value of reminderId is obtained from the return value of publishReminder.)

-

function getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void;

-

function getValidReminders(): Promise<Array<ReminderRequest>>;

-

Obtains all valid reminders set by the current application.

-

function cancelAllReminders(callback: AsyncCallback<void>): void;

-

function cancelAllReminders(): Promise<void>;

-

Cancels all reminders set by the current application.

-

function addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void;

-

function addNotificationSlot(slot: NotificationSlot): Promise<void>;

-

Registers a NotificationSlot instance to be used by the reminder.

-

function removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void;

-

function removeNotificationSlot(slotType: notification.SlotType): Promise<void>;

-

Removes a NotificationSlot instance of a specified type.

-
- -**ActionButtonType** enumerates types of buttons displayed in a reminder notification. - -**Table 2** ActionButtonType enumeration - - - - - - - - - - -

Name

-

Description

-

ACTION_BUTTON_TYPE_CLOSE

-

Close button, which can be tapped to stop the reminder alert tone, close the reminder notification, and cancel the reminder snoozing.

-
- -**ReminderType** enumerates the reminder types. - -**Table 3** ReminderType enumeration - - - - - - - - - - - - - - - - -

Name

-

Description

-

REMINDER_TYPE_TIMER

-

Countdown reminder.

-

REMINDER_TYPE_CALENDAR

-

Calendar reminder.

-

REMINDER_TYPE_ALARM

-

Alarm reminder.

-
- -**ActionButton** defines a button displayed in the reminder notification. - -**Table 4** ActionButton instance - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

title

-

string

-

Yes

-

Text on the button.

-

type

-

ActionButtonType

-

Yes

-

Button type.

-
- -**WantAgent** sets the package and ability that are redirected to when the reminder notification is clicked. - -**Table 5** WantAgent instance - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

pkgName

-

string

-

Yes

-

Name of the package redirected to when the reminder notification is clicked.

-

abilityName

-

string

-

Yes

-

Name of the ability redirected to when the reminder notification is clicked.

-
- -**MaxScreenWantAgent** sets the name of the target package and ability to start automatically when the reminder arrives and the device is not in use. If the device is in use, a notification will be displayed. - -**Table 6** MaxScreenWantAgent instance - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

pkgName

-

string

-

Yes

-

Name of the package that is automatically started when the reminder arrives and the device is not in use.

-

abilityName

-

string

-

Yes

-

Name of the ability that is automatically started when the reminder arrives and the device is not in use.

-
- -**ReminderRequest** defines the reminder to publish. - -**Table 7** ReminderRequest instance - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

reminderType

-

ReminderType

-

Yes

-

Type of the reminder.

-

actionButton

-

[ActionButton?, ActionButton?]

-

No

-

Action button displayed in the reminder notification.

-

wantAgent

-

WantAgent

-

No

-

Information about the ability that is redirected to when the notification is clicked.

-

maxScreenWantAgent

-

MaxScreenWantAgent

-

No

-

Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.

-

ringDuration

-

number

-

No

-

Ring duration.

-

snoozeTimes

-

number

-

No

-

Number of reminder snooze times.

-

timeInterval

-

number

-

No

-

Reminder snooze interval.

-

title

-

string

-

No

-

Reminder title.

-

content

-

string

-

No

-

Reminder content.

-

expiredContent

-

string

-

No

-

Extended content to be displayed when the reminder expires.

-

snoozeContent

-

string

-

No

-

Extended content to be displayed when the reminder is snoozing.

-

notificationId

-

number

-

No

-

Notification ID used by the reminder. For details, see the API reference of the NotificationRequest.setNotificationId(int id) method.

-

slotType

-

SlotType

-

No

-

Type of the slot used by the reminder.

-
- -**ReminderRequestCalendar** extends **ReminderRequest** and defines a reminder for a calendar event. +# Agent-Powered Scheduled Reminder Development + +## When to Use + +You can set your application to call the **ReminderRequest** class to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background, even when your application is frozen or exits. + +## Available APIs + +**reminderAgent** encapsulates the methods for publishing and canceling reminders. + +**Table 1** Major APIs in reminderAgent + + + +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| function publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\): void;
function publishReminder(reminderReq: ReminderRequest): Promise\; | Publishes a scheduled reminder.
The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system. | +| function cancelReminder(reminderId: number, callback: AsyncCallback\): void;
function cancelReminder(reminderId: number): Promise\; | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.) | +| function getValidReminders(callback: AsyncCallback>): void;
function getValidReminders(): Promise>; | Obtains all valid reminders set by the current application. | +| function cancelAllReminders(callback: AsyncCallback\): void;
function cancelAllReminders(): Promise\; | Cancels all reminders set by the current application. | +| function addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback\): void;
function addNotificationSlot(slot: NotificationSlot): Promise; | Registers a NotificationSlot instance to be used by the reminder. | +| function removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback\): void;function removeNotificationSlot(slotType: notification.SlotType): Promise\; | Removes a NotificationSlot instance of a specified type. | + +**ActionButtonType** enumerates types of buttons displayed in a reminder notification. + +**Table 2** ActionButtonType enumeration + + + +| Name | Description | +| ------------------------ | ------------------------------------------------------------ | +| ACTION_BUTTON_TYPE_CLOSE | Close button, which can be tapped to stop the reminder alert tone, close the reminder notification, and cancel the reminder snoozing. | + +**ReminderType** enumerates the reminder types. + +**Table 3** ReminderType enumeration + + + +| Name | Description | +| ---------------------- | ------------------- | +| REMINDER_TYPE_TIMER | Countdown reminder. | +| REMINDER_TYPE_CALENDAR | Calendar reminder. | +| REMINDER_TYPE_ALARM | Alarm reminder. | + +**ActionButton** defines a button displayed in the reminder notification. + +**Table 4** ActionButton instance + + + +| Name | Type | Mandatory | Description | +| ----- | ---------------- | --------- | ------------------- | +| title | string | Yes | Text on the button. | +| type | ActionButtonType | Yes | Button type. | + +**WantAgent** sets the package and ability that are redirected to when the reminder notification is clicked. + +**Table 5** WantAgent instance + + + +| Name | Type | Mandatory | Description | +| ----------- | ------ | --------- | ------------------------------------------------------------ | +| pkgName | string | Yes | Name of the package redirected to when the reminder notification is clicked. | +| abilityName | string | Yes | Name of the ability redirected to when the reminder notification is clicked. | + +**MaxScreenWantAgent** sets the name of the target package and ability to start automatically when the reminder arrives and the device is not in use. If the device is in use, a notification will be displayed. + +**Table 6** MaxScreenWantAgent instance + + + +| Name | Type | Mandatory | Description | +| ----------- | ------ | --------- | ------------------------------------------------------------ | +| pkgName | string | Yes | Name of the package that is automatically started when the reminder arrives and the device is not in use. | +| abilityName | string | Yes | Name of the ability that is automatically started when the reminder arrives and the device is not in use. | + +**ReminderRequest** defines the reminder to publish. + +**Table 7** ReminderRequest instance + + + +| Name | Type | Mandatory | Description | +| ------------------ | ------------------------------ | --------- | ------------------------------------------------------------ | +| reminderType | ReminderType | Yes | Type of the reminder. | +| actionButton | [ActionButton?, ActionButton?] | No | Action button displayed in the reminder notification. | +| wantAgent | WantAgent | No | Information about the ability that is redirected to when the notification is clicked. | +| maxScreenWantAgent | MaxScreenWantAgent | No | Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed. | +| ringDuration | number | No | Ring duration. | +| snoozeTimes | number | No | Number of reminder snooze times. | +| timeInterval | number | No | Reminder snooze interval. | +| title | string | No | Reminder title. | +| content | string | No | Reminder content. | +| expiredContent | string | No | Extended content to be displayed when the reminder expires. | +| snoozeContent | string | No | Extended content to be displayed when the reminder is snoozing. | +| notificationId | number | No | Notification ID used by the reminder. For details, see the API reference of the **NotificationRequest.setNotificationId(int id)** method. | +| slotType | SlotType | No | Type of the slot used by the reminder. | + +**ReminderRequestCalendar** extends **ReminderRequest** and defines a reminder for a calendar event. For the application to run properly, if both **repeatMonths** and **repeatDays** are not specified, the earliest reminder time must be later than the current time. -**Table 8** ReminderRequestCalendar instance - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

dateTime

-

LocalDateTime

-

Yes

-

Reminder time, accurate to the minute.

-

repeatMonths

-

Array<number>

-

No

-

Months in which the reminder repeats. The value range is 1 to 12.

-

repeatDays

-

Array<number>

-

No

-

Date on which the reminder repeats. The value range is 1 to 31.

-
- -**ReminderRequestAlarm** extends **ReminderRequest** and defines a reminder for the alarm clock. - -**Table 9** ReminderRequestAlarm instance - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

hour

-

number

-

Yes

-

Hour portion of the reminder time. The value range is 0 to 23.

-

minute

-

number

-

Yes

-

Minute portion of the reminder time. The value range is 0 to 59.

-

daysOfWeek

-

Array<number>

-

No

-

Days of a week when the reminder repeats. The value range is 1 to 7.

-
- -**ReminderRequestTimer** extends **ReminderRequest** and defines a reminder for a scheduled timer. - -**Table 10** ReminderRequestTimer instance - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

triggerTimeInSeconds

-

number

-

Yes

-

Number of seconds in the countdown timer.

-
- -**LocalDateTime** defines a **LocalDateTime** instance. - -**Table 11** LocalDateTime instance - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

year

-

number

-

Yes

-

Year.

-

month

-

number

-

Yes

-

Month.

-

day

-

number

-

Yes

-

Date.

-

hour

-

number

-

Yes

-

Hour.

-

minute

-

number

-

Yes

-

Minute.

-

second

-

number

-

No

-

Second.

-
- -## How to Develop - ->**NOTE**
->To publish a reminder, your application needs to apply for the **ohos.permission.PUBLISH\_AGENT\_REMINDER** permission. +**Table 8** ReminderRequestCalendar instance -Publish a 10-second countdown reminder. -1. Define a countdown timer instance. - - ``` - import reminderAgent from '@ohos.reminderAgent'; - import notification from '@ohos.notification'; - export default { - // In JS Project: - // timer: { - // In eTS Project: - let timer : reminderAgent.ReminderRequestTimer = { - reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, - triggerTimeInSeconds: 10, - actionButton: [ - { - title: "close", - type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE - } - ], - wantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - maxScreenWantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - title: "this is title", - content: "this is content", - expiredContent: "this reminder has expired", - notificationId: 100, - slotType: notification.SlotType.SOCIAL_COMMUNICATION - } - } - ``` - -2. Publish the reminder. - - ``` - startTimer() { - reminderAgent.publishReminder(this.timer, (err, reminderId) =>{ - this.printInfo(JSON.stringify(err)); - this.printInfo("reminderId:" + reminderId); - }); - } - ``` - - HML page code: - - ``` -
- -
- ``` +| Name | Type | Mandatory | Description | +| ------------ | -------------- | --------- | ------------------------------------------------------------ | +| dateTime | LocalDateTime | Yes | Reminder time, accurate to the minute. | +| repeatMonths | Array\ | No | Months in which the reminder repeats. The value range is 1 to 12. | +| repeatDays | Array\ | No | Date on which the reminder repeats. The value range is 1 to 31. | + +**ReminderRequestAlarm** extends **ReminderRequest** and defines a reminder for the alarm clock. + +**Table 9** ReminderRequestAlarm instance + + + +| Name | Type | Mandatory | Description | +| ---------- | -------------- | --------- | ------------------------------------------------------------ | +| hour | number | Yes | Hour portion of the reminder time. The value range is 0 to 23. | +| minute | number | Yes | Minute portion of the reminder time. The value range is 0 to 59. | +| daysOfWeek | Array\ | No | Days of a week when the reminder repeats. The value range is 1 to 7. | + +**ReminderRequestTimer** extends **ReminderRequest** and defines a reminder for a scheduled timer. + +**Table 10** ReminderRequestTimer instance + + + +| Name | Type | Mandatory | Description | +| -------------------- | ------ | --------- | ----------------------------------------- | +| triggerTimeInSeconds | number | Yes | Number of seconds in the countdown timer. | + +**LocalDateTime** defines a **LocalDateTime** instance. + +**Table 11** LocalDateTime instance + + + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ----------- | +| year | number | Yes | Year. | +| month | number | Yes | Month. | +| day | number | Yes | Date. | +| hour | number | Yes | Hour. | +| minute | number | Yes | Minute. | +| second | number | No | Second. | + +## How to Develop + +> **NOTE** +> To publish a reminder, your application needs to apply for the **ohos.permission.PUBLISH_AGENT_REMINDER** permission. + +Publish a 10-second countdown reminder. + +1. Define a countdown timer instance. + + ``` + import reminderAgent from '@ohos.reminderAgent'; + import notification from '@ohos.notification'; + export default { + // In JS Project: + // timer: { + // In eTS Project: + let timer : reminderAgent.ReminderRequestTimer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 10, + actionButton: [ + { + title: "close", + type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE + } + ], + wantAgent: { + pkgName: "com.example.device", + abilityName: "com.example.device.MainAbility" + }, + maxScreenWantAgent: { + pkgName: "com.example.device", + abilityName: "com.example.device.MainAbility" + }, + title: "this is title", + content: "this is content", + expiredContent: "this reminder has expired", + notificationId: 100, + slotType: notification.SlotType.SOCIAL_COMMUNICATION + } + } + ``` + +2. Publish the reminder. + + ``` + startTimer() { + reminderAgent.publishReminder(this.timer, (err, reminderId) =>{ + this.printInfo(JSON.stringify(err)); + this.printInfo("reminderId:" + reminderId); + }); + } + ``` + + HML page code: + + ``` +
+ +
+ ``` Sample code for defining a calendar reminder instance: @@ -689,5 +297,4 @@ let alarm : reminderAgent.ReminderRequestAlarm = { notificationId: 100, slotType: notification.SlotType.SOCIAL_COMMUNICATION } -``` - +``` \ No newline at end of file diff --git a/en/application-dev/background-task-management/background-task-dev-guide.md b/en/application-dev/background-task-management/background-task-dev-guide.md index 74874b31163501aa7347264824842437a2f10008..f91d0445a535091103051fb6153df1e74f18f03c 100644 --- a/en/application-dev/background-task-management/background-task-dev-guide.md +++ b/en/application-dev/background-task-management/background-task-dev-guide.md @@ -289,4 +289,4 @@ export default { The following sample is provided to help you better understand how to develop background task management: -- [BackgroundTaskManager: Background Task Management (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ResourcesSchedule/BackgroundTaskManager) +- [`BackgroundTaskManager`: Background Task Management (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ResourcesSchedule/BackgroundTaskManager) diff --git a/en/application-dev/connectivity/ipc-rpc-development-guideline.md b/en/application-dev/connectivity/ipc-rpc-development-guideline.md index 03019858805cff17ef97b4c7227ee5c86947536b..3d541e4832aa72a585972d327e2fb2f31a077fa6 100644 --- a/en/application-dev/connectivity/ipc-rpc-development-guideline.md +++ b/en/application-dev/connectivity/ipc-rpc-development-guideline.md @@ -133,13 +133,13 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat ``` // Register the TestAbilityStub instance with the SystemAbilityManager on the same device as the SA. auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - samgr->AddSystemAbility(said, new TestAbility()); + samgr->AddSystemAbility(saId, new TestAbility()); // Register the TestAbilityStub instance with the SystemAbilityManager on a different device. auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); ISystemAbilityManager::SAExtraProp saExtra; saExtra.isDistributed = true; // Set a distributed SA. - int result = samgr->AddSystemAbility(said, new TestAbility(), saExtra); + int result = samgr->AddSystemAbility(saId, new TestAbility(), saExtra); ``` 6. Obtain the SA. @@ -149,12 +149,12 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat ``` // Obtain the proxy of the SA registered on the local device. sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - sptr remoteObject = samgr->GetSystemAbility(said); + sptr remoteObject = samgr->GetSystemAbility(saId); sptr testAbility = iface_cast(remoteObject); // Use the iface_cast macro to convert the proxy to a specific type. // Obtain the proxies of the SAs registered with other devices. sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - sptr remoteObject = samgr->GetSystemAbility(sdid, deviceId); // deviceId identifies a device. + sptr remoteObject = samgr->GetSystemAbility(saId, deviceId); // deviceId identifies a device. sptr proxy(new TestAbilityProxy(remoteObject)); // Construct a proxy. ``` diff --git a/en/application-dev/database/database-distributedobject-guidelines.md b/en/application-dev/database/database-distributedobject-guidelines.md index 516ed427b9b8d613b832b430cc63e7d3fa4cd30f..86392551501483b40e69ce3fdcad0e3c5f71e92c 100644 --- a/en/application-dev/database/database-distributedobject-guidelines.md +++ b/en/application-dev/database/database-distributedobject-guidelines.md @@ -165,14 +165,4 @@ The following example shows how to implement a distributed data object synchroni ```js local_object.setSessionId(""); - ``` - -## Samples - -The following example is provided for you to better understand the development of distributed data objects: - -- [Distributed Notepad](https://gitee.com/openharmony/distributeddatamgr_objectstore/tree/master/samples/distributedNotepad) - - -When an event of the Notepad app occurs on a device, such as a note is added, the tile or content of a note is changed, or the event list is cleared, the change will be synchronized to other devices in the trusted network. - + ``` \ No newline at end of file diff --git a/en/application-dev/database/database-mdds-guidelines.md b/en/application-dev/database/database-mdds-guidelines.md index fb45be2adf83aa7c3a1dac6cc875926c3c22a705..309d2a38e4cbcab79a102b809bb9444cf9a8e1ee 100644 --- a/en/application-dev/database/database-mdds-guidelines.md +++ b/en/application-dev/database/database-mdds-guidelines.md @@ -178,7 +178,3 @@ 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 Data Management (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore) -- [Distributed Data Service](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 d43b11ff62e73d65de6d77623641b7748a82c824..cdcbf0b033288458f2d0ae4192476d86bc9f38b5 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -15,10 +15,10 @@ The following table describes the APIs available for creating and deleting an RD | API| Description| | -------- | -------- | -|getRdbStore(config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void | Obtains an RDB store. This method uses a callback to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **config**: configuration of the RDB store.
- **version**: RDB version.
- **callback**: callback invoked to return the RDB store obtained.| -|getRdbStore(config: StoreConfig, version: number): Promise<RdbStore> | Obtains an RDB store. This method uses a promise to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **config**: configuration of the RDB store.
- **version**: RDB version.| -|deleteRdbStore(name: string, callback: AsyncCallback<void>): void | Deletes an RDB store. This method uses a callback to return the result.
- **name**: RDB store to delete.
- **callback**: callback invoked to return the result.| -| deleteRdbStore(name: string): Promise<void> | Deletes an RDB store. This method uses a promise to return the result.
- **name**: RDB store to delete.| +|getRdbStore(config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void | Obtains an RDB store. This method uses a callback to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **config**: configuration of the RDB store.
- **version**: RDB version.
- **callback**: callback invoked to return the RDB store obtained.| +|getRdbStore(config: StoreConfig, version: number): Promise<RdbStore> | Obtains an RDB store. This method uses a promise to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **config**: configuration of the RDB store.
- **version**: RDB version.| +|deleteRdbStore(name: string, callback: AsyncCallback<void>): void | Deletes an RDB store. This method uses a callback to return the result.
- **name**: RDB store to delete.
- **callback**: callback invoked to return the result.| +| deleteRdbStore(name: string): Promise<void> | Deletes an RDB store. This method uses a promise to return the result.
- **name**: RDB store to delete.| ### Managing Data in an RDB Store @@ -32,8 +32,8 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class| API| Description| | -------- | -------- | -------- | - | RdbStore | insert(name: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table. This method uses a callback to return the result.
- **name**: 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(name: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This method uses a promise to return the result.
- **name**: name of the target table.
- **values**: data to be inserted into the table.| + | RdbStore | insert(name: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table. This method uses a callback to return the result.
- **name**: 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(name: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This method uses a promise to return the result.
- **name**: name of the target table.
- **values**: data to be inserted into the table.| - **Updating data** @@ -43,8 +43,8 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class| API| Description| | -------- | -------- | -------- | - | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **rdbPredicates**: conditions for updating data.
- **callback**: callback invoked to return the number of rows updated.| - | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates): Promise | Updates data in the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **rdbPredicates**: conditions for updating data.| + | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **rdbPredicates**: conditions for updating data.
- **callback**: callback invoked to return the number of rows updated.| + | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates): Promise\ | Updates data in the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **rdbPredicates**: conditions for updating data.| - **Deleting data** @@ -54,8 +54,8 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class| API| Description| | -------- | -------- | -------- | - | RdbStore | delete(rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void | Deletes data from the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **rdbPredicates**: conditions for deleting data.
- **callback**: callback invoked to return the number of rows deleted.| - | RdbStore | delete(rdbPredicates: RdbPredicates): Promise | Deletes data from the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **rdbPredicates**: conditions for deleting data.| + | RdbStore | delete(rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void | Deletes data from the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **rdbPredicates**: conditions for deleting data.
- **callback**: callback invoked to return the number of rows deleted.| + | RdbStore | delete(rdbPredicates: RdbPredicates): Promise\ | Deletes data from the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **rdbPredicates**: conditions for deleting data.| - **Querying data** @@ -68,10 +68,10 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class| API| Description| | -------- | -------- | -------- | - | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array, callback: AsyncCallback<ResultSet>): void | Queries data in the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **rdbPredicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| - | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array): Promise<ResultSet> | Queries data in the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **rdbPredicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| - | RdbStore | querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store using the specified SQL statement. This method uses a callback to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| - | RdbStore | querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> | Queries data in the RDB store using the specified SQL statement. This method uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| + | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array, callback: AsyncCallback<ResultSet>): void | Queries data in the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **rdbPredicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array): Promise<ResultSet> | Queries data in the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **rdbPredicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| + | RdbStore | querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store using the specified SQL statement. This method uses a callback to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + | RdbStore | querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> | Queries data in the RDB store using the specified SQL statement. This method uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| ### Using Predicates @@ -81,74 +81,76 @@ The RDB provides **RdbPredicates** for you to set database operation conditions. | Class| API| Description| | -------- | -------- | -------- | -| RdbPredicates |inDevices(devices: Array): RdbPredicates | Specifies remote devices on the network with RDB stores to be synchronized.
- **devices**: IDs of the remote devices on the network.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates |inAllDevices(): RdbPredicates | Connects to all remote devices on the network with RDB stores to be synchronized.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | beginWrap(): RdbPredicates | Adds a left parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a left parenthesis.| -| RdbPredicates | endWrap(): RdbPredicates | Adds a right parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a right parenthesis.| -| RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the OR condition.| -| RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the AND condition.| -| RdbPredicates | contains(field: string, value: string): RdbPredicats | Sets the **RdbPredicates** to match a string containing the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified string.| -| RdbPredicates | beginsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that starts with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | endsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that ends with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | isNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | isNotNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is not null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | like(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that is similar to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | glob(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match the specified string.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | between(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value within the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicatesgr | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | lessThan(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | orderByAsc(field: string): RdbPredicates | Sets the **RdbPredicates** to match the column with values sorted in ascending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | orderByDesc(field: string): RdbPredicates | Sets the **RdbPredicates** to match the column with values sorted in descending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | distinct(): RdbPredicates | Sets the **RdbPredicates** to filter out duplicate records.
- **RdbPredicates**: returns a **RdbPredicates** object that can filter out duplicate records.| -| RdbPredicates | limitAs(value: number): RdbPredicates | Sets the **RdbPredicates** to specify the maximum number of records.
- **value**: maximum number of records.
- **RdbPredicates**: returns a **RdbPredicates** object that can be used to set the maximum number of records.| -| RdbPredicates | offsetAs(rowOffset: number): RdbPredicates | Sets the **RdbPredicates** to specify the start position of the returned result.
- **rowOffset**: start position of the returned result. The value is a positive integer.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the start position of the returned result.| -| RdbPredicates | groupBy(fields: Array<string>): RdbPredicates | Sets the **RdbPredicates** to group rows that have the same value into summary rows.
- **fields**: names of the columns grouped for querying data.
- **RdbPredicates**: returns a **RdbPredicates** object that groups rows with the same value.| -| RdbPredicates | indexedBy(indexName: string): RdbPredicates | Sets the **RdbPredicates** to specify the index column.
- **indexName**: name of the index column.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the index column.| -| RdbPredicates | in(field: string, value: Array<ValueType>): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | notIn(field: string, value: Array<ValueType>): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates |inDevices(devices: Array\): RdbPredicates | Specifies remote devices on the network with RDB stores to be synchronized.
- **devices**: IDs of the remote devices on the network.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates |inAllDevices(): RdbPredicates | Connects to all remote devices on the network with RDB stores to be synchronized.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | beginWrap(): RdbPredicates | Adds a left parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a left parenthesis.| +| RdbPredicates | endWrap(): RdbPredicates | Adds a right parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a right parenthesis.| +| RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the OR condition.| +| RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the AND condition.| +| RdbPredicates | contains(field: string, value: string): RdbPredicats | Sets the **RdbPredicates** to match a string containing the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified string.| +| RdbPredicates | beginsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that starts with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | endsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that ends with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | isNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | isNotNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is not null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | like(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that is similar to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | glob(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match the specified string.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | between(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value within the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicatesgr | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | lessThan(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | orderByAsc(field: string): RdbPredicates | Sets the **RdbPredicates** to match the column with values sorted in ascending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | orderByDesc(field: string): RdbPredicates | Sets the **RdbPredicates** to match the column with values sorted in descending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | distinct(): RdbPredicates | Sets the **RdbPredicates** to filter out duplicate records.
- **RdbPredicates**: returns a **RdbPredicates** object that can filter out duplicate records.| +| RdbPredicates | limitAs(value: number): RdbPredicates | Sets the **RdbPredicates** to specify the maximum number of records.
- **value**: maximum number of records.
- **RdbPredicates**: returns a **RdbPredicates** object that can be used to set the maximum number of records.| +| RdbPredicates | offsetAs(rowOffset: number): RdbPredicates | Sets the **RdbPredicates** to specify the start position of the returned result.
- **rowOffset**: start position of the returned result. The value is a positive integer.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the start position of the returned result.| +| RdbPredicates | groupBy(fields: Array<string>): RdbPredicates | Sets the **RdbPredicates** to group rows that have the same value into summary rows.
- **fields**: names of the columns grouped for querying data.
- **RdbPredicates**: returns a **RdbPredicates** object that groups rows with the same value.| +| RdbPredicates | indexedBy(indexName: string): RdbPredicates | Sets the **RdbPredicates** to specify the index column.
- **indexName**: name of the index column.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the index column.| +| RdbPredicates | in(field: string, value: Array<ValueType>): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | notIn(field: string, value: Array<ValueType>): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| ### Using the Result Set A result set can be regarded as a row of data in the queried results. It allows you to traverse and access the data you have queried. The following table describes the external APIs of **ResultSet**. -> ![icon-notice.gif](public_sys-resources/icon-notice.gif) **NOTICE**
+> **NOTICE**
> After a result set is used, you must call the **close()** method to close it explicitly. **Table 7** APIs for using the result set | Class| API| Description| | -------- | -------- | -------- | -| ResultSet | goTo(offset:number): boolean | Moves the result set forwards or backwards by the specified offset relative to its current position.| -| ResultSet | goToRow(position: number): boolean | Moves the result set to the specified row.| -| ResultSet | goToNextRow(): boolean | Moves the result set to the next row.| -| ResultSet | goToPreviousRow(): boolean | Moves the result set to the previous row.| -| ResultSet | getColumnIndex(columnName: string): number | Obtains the column index based on the specified column name.| -| ResultSet | getColumnName(columnIndex: number): string | Obtains the column name based on the specified column index.| -| ResultSet | goToFirstRow(): boolean | Checks whether the result set is located in the first row.| -| ResultSet | goToLastRow(): boolean | Checks whether the result set is located in the last row.| -| ResultSet | getString(columnIndex: number): string | Obtains the value in the specified column of the current row, in a string.| -| ResultSet | getBlob(columnIndex: number): Uint8Array | Obtains the values in the specified column of the current row, in a byte array.| -| ResultSet | getDouble(columnIndex: number): number | Obtains the values in the specified column of the current row, in double.| -| ResultSet | isColumnNull(columnIndex: number): boolean | Checks whether the value in the specified column of the current row is null.| -| ResultSet | close(): void | Closes the result set.| +| ResultSet | goTo(offset:number): boolean | Moves the result set forwards or backwards by the specified offset relative to its current position.| +| ResultSet | goToRow(position: number): boolean | Moves the result set to the specified row.| +| ResultSet | goToNextRow(): boolean | Moves the result set to the next row.| +| ResultSet | goToPreviousRow(): boolean | Moves the result set to the previous row.| +| ResultSet | getColumnIndex(columnName: string): number | Obtains the column index based on the specified column name.| +| ResultSet | getColumnName(columnIndex: number): string | Obtains the column name based on the specified column index.| +| ResultSet | goToFirstRow(): boolean | Checks whether the result set is located in the first row.| +| ResultSet | goToLastRow(): boolean | Checks whether the result set is located in the last row.| +| ResultSet | getString(columnIndex: number): string | Obtains the value in the specified column of the current row, in a string.| +| ResultSet | getBlob(columnIndex: number): Uint8Array | Obtains the values in the specified column of the current row, in a byte array.| +| ResultSet | getDouble(columnIndex: number): number | Obtains the values in the specified column of the current row, in double.| +| ResultSet | isColumnNull(columnIndex: number): boolean | Checks whether the value in the specified column of the current row is null.| +| ResultSet | close(): void | Closes the result set.| ### Setting Distributed Tables +>**CAUTION**
ohos.permission.DISTRIBUTED_DATASYNC is requied for using the **setDistributedTables**, **obtainDistributedTableName**, **sync**, **on**, and **off** APIs of **RdbStore**. + **Setting Distributed Tables** **Table 8** APIs for setting distributed tables | Class| API| Description| | -------- | -------- | -------- | -| RdbStore | setDistributedTables(tables: Array, callback: AsyncCallback): void;| Sets a list of distributed tables. This method uses a callback to return the result.
-  **tables**: names of the distributed tables to set.
- **callback**: callback invoked to return the result.| -| RdbStore | setDistributedTables(tables: Array): Promise; | Sets a list of distributed tables. This method uses a promise to return the result.
-  **tables**: names of the distributed tables to set.| +| RdbStore | setDistributedTables(tables: Array\, callback: AsyncCallback\): void | Sets a list of distributed tables. This method uses a callback to return the result.
- **tables**: names of the distributed tables to set.
- **callback**: callback invoked to return the result.| +| RdbStore | setDistributedTables(tables: Array\): Promise\ | Sets a list of distributed tables. This method uses a promise to return the result.
- **tables**: names of the distributed tables to set.| **Obtaining the Distributed Table Name for a Remote Device** @@ -158,8 +160,8 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore | obtainDistributedTableName(device: string, table: string, callback: AsyncCallback): void; | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is used to query the RDB store of the remote device. This method uses a callback to return the result.
- **device**: remote device.
-  **table**: local table name.
-  **callback**: callback used to return the result. If the operation is successful, the distributed table name of the remote device will be returned. | -| RdbStore | obtainDistributedTableName(device: string, table: string): Promise; | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is used to query the RDB store of the remote device. This method uses a promise to return the result.
- **device**: remote device.
-  **table**: local table name.| +| RdbStore | obtainDistributedTableName(device: string, table: string, callback: AsyncCallback\): void | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is used to query the RDB store of the remote device. This method uses a callback to return the result.
- **device**: remote device.
- **table**: local table name.
- **callback**: callback used to return the result. If the operation is successful, the distributed table name of the remote device will be returned. | +| RdbStore | obtainDistributedTableName(device: string, table: string): Promise\ | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is used to query the RDB store of the remote device. This method uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.| **Synchronizing Data Between Devices** @@ -167,8 +169,8 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback>): void;| Synchronizes data between devices. This method uses a callback to return the result.
- **mode**: data synchronization mode. **SYNC\_MODE\_PUSH** means to push data from the local device to a remote device. **SYNC\_MODE\_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized.
- **callback**: callback invoked to return the result. In the result, **string** indicates the device ID, and **number** indicates the synchronization status of each device. The value **0** indicates a success, and other values indicate a failure.| -| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise>;| Synchronizes data between devices. This method uses a promise to return the result.
- **mode**: data synchronization mode. **SYNC\_MODE\_PUSH** means to push data from the local device to a remote device. **SYNC\_MODE\_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized. | +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback\>): void | Synchronizes data between devices. This method uses a callback to return the result.
- **mode**: data synchronization mode. **SYNC\_MODE\_PUSH** means to push data from the local device to a remote device. **SYNC\_MODE\_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized.
- **callback**: callback invoked to return the result. In the result, **string** indicates the device ID, and **number** indicates the synchronization status of each device. The value **0** indicates a success, and other values indicate a failure.| +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This method uses a promise to return the result.
- **mode**: data synchronization mode. **SYNC\_MODE\_PUSH** means to push data from the local device to a remote device. **SYNC\_MODE\_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized. | **Registering an RDB Store Observer** @@ -176,7 +178,7 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore |on(event: 'dataChange', type: SubscribeType, observer: Callback>): void;| Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE\_TYPE\_REMOTE** means to subscribe to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| +| RdbStore |on(event: 'dataChange', type: SubscribeType, observer: Callback\>): void| Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE\_TYPE\_REMOTE** means to subscribe to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| **Unregistering an RDB Store Observer** @@ -184,7 +186,7 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback>): void;| Unregisters the observer of the specified type for the RDB store. This method uses a callback to return the result.
-  **type**: subscription type. **SUBSCRIBE\_TYPE\_REMOTE** means to subscribe to remote data changes.
-  **observer**: observer to unregister.| +| 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.| ## How to Develop @@ -242,24 +244,37 @@ You can obtain the distributed table name for a remote device based on the local ``` 4. Set the distributed tables to be synchronized. - 1. Set the distributed tables. - 2. Check whether the setting is successful. + + 1. Add the following permission to the permission configuration file: + ```js + "requestPermissions": + { + "name": "ohos.permission.DISTRIBUTED_DATASYNC" + } + ``` + 2. Obtain the required permission. + 3. Set the distributed tables. + 4. Check whether the setting is successful. The sample code is as follows: - ```js - let promise = rdbStore.setDistributedTables(["test"]) - promise.then(() => { - console.info("setDistributedTables success.") - }).catch((err) => { - console.info("setDistributedTables failed.") - }) - ``` + ```js + let context = featureAbility.getContext(); + context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { + console.info(`result.requestCode=${result.requestCode}`) + }) + let promise = rdbStore.setDistributedTables(["test"]) + promise.then(() => { + console.info("setDistributedTables success.") + }).catch((err) => { + console.info("setDistributedTables failed.") + }) + ``` - 5. Synchronize data across devices. +5. Synchronize data across devices. 1. Constructs an **RdbPredicates** object to specify remote devices within the network to be synchronized. 2. Call the **sync()** method to synchronize data. - 3. Check whether the data synchronization is successful. + 3. Check whether data synchronization is successful. The sample code is as follows: 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 06edad460749ab7ef5cb00bb820489a8368c01f8..c4e4fdf3850f4bd3b1b8f6902133835764414cb3 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,6 +3,7 @@ ## 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 @@ -19,9 +20,20 @@ import stats from '@ohos.bundleState'; | function queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback<BundleActiveInfoResponse>): void | Queries the application usage duration statistics based on the specified start time and end time.| | function queryCurrentBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void | Queries events of this application based on the specified start time and end time.| | function queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number, callback: AsyncCallback<Array<BundleStateInfo>>): void | Queries the application usage duration statistics in the specified time frame at the specified interval (daily, weekly, monthly, or annually).| -| function queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void | Queries the priority group of the current invoker application.| +| 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 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.| +| function 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.| +| function setBundleGroup(bundleName : string, newGroup: GroupType, callback: AsyncCallback>boolean>): void | Sets the group for the application specified by **bundleName**. This API uses an asynchronous callback to return the result.| +| function setBundleGroup(bundleName : string, newGroup : GroupType): Promise>boolean>; | Sets the group for the application specified by **bundleName**. This API uses a promise to return the result.| +| function registerGroupCallBack(callback: Callback>BundleActiveGroupCallbackInfo>, callback: AsyncCallback>boolean>): void | Registers a callback for application group changes. When an application group of the user changes, the change is returned to all applications that have registered the callback. This API uses an asynchronous callback to return the result.| +| function registerGroupCallBack(callback: Callback>BundleActiveGroupCallbackInfo>): Promise>boolean>; | Registers a callback for application group changes. When an application group of the user changes, the change is returned to all applications that have registered the callback. This API uses a promise to return the result.| +| function unRegisterGroupCallBack(callback: AsyncCallback>boolean>): void | Deregisters the callback for application group changes. This API uses an asynchronous callback to return the result.| +| function unRegisterGroupCallBack(): Promise>boolean>; | Deregisters the callback for application group changes. This API uses a promise to return the result.| ## How to Develop @@ -44,7 +56,7 @@ import stats from '@ohos.bundleState'; ```js import stats from '@ohos.bundleState' - // Use a promise to return the result. + // Promise mode stats.queryBundleActiveStates(0, 20000000000000).then( res => { console.log('BUNDLE_ACTIVE queryBundleActiveStates promise success.'); for (let i = 0; i < res.length; i++) { @@ -55,7 +67,7 @@ import stats from '@ohos.bundleState'; console.log('BUNDLE_ACTIVE queryBundleActiveStates promise failed, because: ' + err.code); }); - // Use an asynchronous callback to return the result. + // Asynchronous callback mode stats.queryBundleActiveStates(0, 20000000000000, (err, res) => { if (err) { console.log('BUNDLE_ACTIVE queryBundleActiveStates callback failed, because: ' + err.code); @@ -74,7 +86,7 @@ import stats from '@ohos.bundleState'; ```js import stats from '@ohos.bundleState' - // Use a promise to return the result. + // Promise mode stats.queryBundleStateInfos(0, 20000000000000).then( res => { console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.'); let i = 1; @@ -87,7 +99,7 @@ import stats from '@ohos.bundleState'; console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code); }); - // Use an asynchronous callback to return the result. + // Asynchronous callback mode stats.queryBundleStateInfos(0, 20000000000000, (err, res) => { if (err) { console.log('BUNDLE_ACTIVE queryBundleStateInfos callback failed, because: ' + err.code); @@ -108,7 +120,7 @@ import stats from '@ohos.bundleState'; ```js import stats from '@ohos.bundleState' - // Use a promise to return the result. + // Promise mode stats.queryCurrentBundleActiveStates(0, 20000000000000).then( res => { console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.'); for (let i = 0; i < res.length; i++) { @@ -119,7 +131,7 @@ import stats from '@ohos.bundleState'; console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failed, because: ' + err.code); }); - // Use an asynchronous callback to return the result. + // Asynchronous callback mode stats.queryCurrentBundleActiveStates(0, 20000000000000, (err, res) => { if (err) { console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback failed, because: ' + err.code); @@ -138,7 +150,7 @@ import stats from '@ohos.bundleState'; ```js import stats from '@ohos.bundleState' - // Use a promise to return the result. + // Promise mode stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then( res => { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.'); for (let i = 0; i < res.length; i++) { @@ -149,7 +161,7 @@ import stats from '@ohos.bundleState'; console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failed, because: ' + err.code); }); - // Use an asynchronous callback to return the result. + // Asynchronous callback mode stats.queryBundleStateInfoByInterval(0, 0, 20000000000000, (err, res) => { if (err) { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback failed, because: ' + err.code); @@ -163,19 +175,19 @@ import stats from '@ohos.bundleState'; }); ``` -6. Query the priority group of the current invoker application. This requires no permission to be configured in the **config.json** file. +6. Query the priority group of the current application. This requires no permission to be configured in the **config.json** file. ```js import stats from '@ohos.bundleState' - - // Use a promise to return the result. + + // Promise mode stats.queryAppUsagePriorityGroup().then( res => { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res)); }).catch( err => { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code); }); - - // Use an asynchronous callback to return the result. + + // Callback mode stats.queryAppUsagePriorityGroup((err, res) => { if (err) { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failed. because: ' + err.code); @@ -184,20 +196,20 @@ 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. + +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' - // Use a promise to return the result. + // Promise mode stats.isIdleState("com.ohos.camera").then( res => { console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res)); }).catch( err => { console.log('BUNDLE_ACTIVE isIdleState promise failed, because: ' + err.code); }); - // Use an asynchronous callback to return the result. + // Asynchronous callback mode stats.isIdleState("com.ohos.camera", (err, res) => { if (err) { console.log('BUNDLE_ACTIVE isIdleState callback failed, because: ' + err.code); @@ -212,7 +224,7 @@ import stats from '@ohos.bundleState'; ```js import stats from '@ohos.bundleState' - // Use a promise to return the result. + // Promise mode stats.getRecentlyUsedModules(1000).then( res => { console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded'); for (let i = 0; i < res.length; i++) { @@ -223,7 +235,7 @@ import stats from '@ohos.bundleState'; console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise failed, because: ' + err.code); }); - // Use a promise to return the result when maxNum is not specified. + // Promise mode when maxNum is not specified stats.getRecentlyUsedModules().then( res => { console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded'); for (let i = 0; i < res.length; i++) { @@ -234,7 +246,7 @@ import stats from '@ohos.bundleState'; console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise failed, because: ' + err.code); }); - // Use an asynchronous callback to return the result. + // Asynchronous callback mode stats.getRecentlyUsedModules(1000,(err, res) => { if(err) { console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code); @@ -247,7 +259,7 @@ import stats from '@ohos.bundleState'; } }); - // Use an asynchronous callback to return the result when maxNum is not specified. + // Asynchronous callback mode when maxNum is not specified stats.getRecentlyUsedModules((err, res) => { if(err) { console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code); @@ -260,3 +272,168 @@ import stats from '@ohos.bundleState'; } }); ``` + +9. Query the number of notifications from all applications based on the specified start time and end time. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured in the **config.json** file. + + ```js + import stats from '@ohos.bundleState' + + // Promise mode + 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 => { + console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise failed, because: ' + err.code); + }); + + // Asynchronous callback mode + stats.queryAppNotificationNumber(0, 20000000000000, (err, res) => { + if (err) { + console.log('BUNDLE_ACTIVE queryAppNotificationNumber callback failed, because: ' + err.code); + } else { + console.log('BUNDLE_ACTIVE queryAppNotificationNumber callback success.'); + console.log('BUNDLE_ACTIVE queryAppNotificationNumber callback result ' + JSON.stringify(res)); + } + }); + ``` + +10. Query statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured in the **config.json** file. + + ```js + import stats from '@ohos.bundleState' + + // Promise mode + 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 => { + console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise failed, because: ' + err.code); + }); + + // Asynchronous callback mode + stats.queryBundleActiveEventStates(0, 20000000000000, (err, res) => { + if (err) { + console.log('BUNDLE_ACTIVE queryBundleActiveEventStates callback failed, because: ' + err.code); + } else { + console.log('BUNDLE_ACTIVE queryBundleActiveEventStates callback success.'); + console.log('BUNDLE_ACTIVE queryBundleActiveEventStates callback result ' + JSON.stringify(res)); + } + }); + ``` + +11. Query the priority group of the current application. This requires no permission to be configured in the **config.json** file. Query the priority group of a specified application. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured in the **config.json** file. + + ```js + import stats from '@ohos.bundleState' + + // Promise mode without parameters + stats.queryAppUsagePriorityGroup().then( res => { + console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res)); + }).catch( err => { + console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code); + }); + + // Asynchronous callback mode without parameters + stats.queryAppUsagePriorityGroup((err, res) => { + if (err) { + console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failed. because: ' + err.code); + } else { + console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res)); + } + }); + + // Promise mode with parameters + stats.queryAppUsagePriorityGroup(this.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); + }); + + // Asynchronous callback mode with parameters + stats.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)); + } + }); + ``` + +11. Set the group for the application specified by **bundleName**. + + ```javascript + import stats from '@ohos.bundleState' + + // Promise mode + 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) { + console.log('BUNDLE_ACTIVE SetBundleGroup callback failed. because: ' + err.code); + } else { + console.log('BUNDLE_ACTIVE SetBundleGroup callback succeeded.'); + } + }); + ``` + +12. Register a callback for application group changes. When an application group of the user changes, the change is returned to all applications that have registered the callback. + + ```javascript + import stats from '@ohos.bundleState' + + // Promise mode + 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); + }; + stats.registerGroupCallBack(onBundleGroupChanged).then( () => { + console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise succeeded.'); + }).catch( err => { + console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise failed. because: ' + err.code); + }); + // Asynchronous callback mode + 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); + }; + 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( () => { + console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise succeeded.'); + }).catch( err => { + console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise failed. because: ' + err.code); + }); + //callback + 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-usage-statistics/device-usage-statistics-overview.md b/en/application-dev/device-usage-statistics/device-usage-statistics-overview.md index 696a32c18ca974da852fa8600d126ca692d81f7d..e9d669f7973dce4360c617a6872fa3c86adf481f 100644 --- a/en/application-dev/device-usage-statistics/device-usage-statistics-overview.md +++ b/en/application-dev/device-usage-statistics/device-usage-statistics-overview.md @@ -12,22 +12,29 @@ Currently you can have access to statistics on the application usage, and notifi 3. Upon start of a new day - **The application usage statistics can include the following**: -1. Events of all applications based on the specified start time and end time +1. Events of all applications based on the specified start time and end time +2. Application usage duration statistics based on the specified start time and end time +3. Events of the current application based on the specified start time and end time +4. Application usage duration statistics in the specified time frame at the specified interval (daily, weekly, monthly, or annually) +5. Priority group of the current invoker application +6. Whether a specific application is in the idle state +7. Number of FA usage records specified by **maxNum**, sorted by time (most recent first). If **maxNum** is not specified, the default value **1000** will be used. +8. Number of notifications from applications based on the specified start time and end time +9. Statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time +9. Priority group of the invoker application or a specified application -2. Application usage duration statistics based on the specified start time and end time +- **The setters can be used to:** -3. Events of the current application based on the specified start time and end time + Set the group for the application specified by **bundleName**. -4. Application usage duration statistics in the specified time frame at the specified interval (daily, weekly, monthly, or annually) +- **The registration APIs can be used to:** -5. Priority group of the current invoker application + Register a callback for application group changes. When an application group of the user changes, the change is returned to all applications that have registered the callback. -6. Whether a specific application is in the idle state +- **The deregistration APIs can be used to:** -7. The number of FA usage records specified by **maxNum**, sorted by time (most recent first) - - If **maxNum** is not specified, the default value **1000** will be used. + Deregister the callback for application group changes. ### Required Permissions -- The **queryBundleActiveStates**, **queryBundleStateInfos**, and **queryBundleStateInfoByInterval** APIs used for device usage statistics are system APIs. Before calling these APIs, you need to apply for the **ohos.permission.BUNDLE_ACTIVE_INFO** permission. -- This permission is not required for calling **queryCurrentBundleActiveStates**, **queryAppUsagePriorityGroup**, and **isIdleState**, which are third-party APIs. +- Before calling the following system APIs, you need to apply for the **ohos.permission.BUNDLE_ACTIVE_INFO** permission: **queryBundleActiveStates**, **queryBundleStateInfos**, **queryBundleStateInfoByInterval**, **queryBundleActiveEventStates**, **queryAppNotificationNumber**, **queryAppUsagePriorityGroup(bundleName?)**, **setBundleGroup**, **registerGroupCallBack**, and **unRegisterGroupCallBack**. +- This permission is not required for calling third-party APIs: **queryCurrentBundleActiveStates**, **queryAppUsagePriorityGroup()**, and **isIdleState**. diff --git a/en/application-dev/device/usb-guidelines.md b/en/application-dev/device/usb-guidelines.md index 46304e882adcc8f8fbd69daf30cbe58a565696cd..e14b8bc1fa4e6755108faa6f9d0636f327bc95e4 100644 --- a/en/application-dev/device/usb-guidelines.md +++ b/en/application-dev/device/usb-guidelines.md @@ -1,93 +1,34 @@ -# USB Service Development +# USB Service Development -## When to Use +## When to Use In Host mode, you can obtain the list of connected devices, enable or disable the devices, manage device access permissions, and perform data transfer or control transfer. -## APIs +## APIs The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management. -The following table lists the USB APIs currently available. For details, see the _API Reference_. +The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usb.md). **Table 1** Open USB APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

API

-

Description

-

hasRight(deviceName: string): boolean

-

Checks whether the user, for example, the application or system, has the device access permissions. The value true is returned if the user has the device access permissions; the value false is returned otherwise.

-

requestRight(deviceName: string): Promise<boolean>

-

Requests the temporary permission for a given application to access the USB device.

-

connectDevice(device: USBDevice): Readonly<USBDevicePipe>

-

Connects to the USB device based on the device information returned by getDevices().

-

getDevices(): Array<Readonly<USBDevice>>

-

Obtains the USB device list.

-

setConfiguration(pipe: USBDevicePipe, config: USBConfig): number

-

Sets the USB device configuration.

-

setInterface(pipe: USBDevicePipe, iface: USBInterface): number

-

Sets a USB interface.

-

claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number

-

Claims a USB interface

-

function bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise<number>

-

Performs bulk transfer.

-

closePipe(pipe: USBDevicePipe): number

-

Closes a USB device pipe.

-

releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number

-

Releases a USB interface.

-

getFileDescriptor(pipe: USBDevicePipe): number

-

Obtains the file descriptor.

-

getRawDescriptor(pipe: USBDevicePipe): Uint8Array

-

Obtains the raw USB descriptor.

-

controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise<number>

-

Performs control transfer.

-
- -## How to Develop +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| hasRight(deviceName: string): boolean | Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise. | +| requestRight(deviceName: string): Promise\ | Requests the temporary permission for a given application to access the USB device. | +| connectDevice(device: USBDevice): Readonly\ | Connects to the USB device based on the device information returned by **getDevices()**. | +| getDevices(): Array> | Obtains the USB device list. | +| setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. | +| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | +| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface | +| function bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise\ | Performs bulk transfer. | +| closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. | +| releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. | +| getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. | +| getRawDescriptor(pipe: USBDevicePipe): Uint8Array | Obtains the raw USB descriptor. | +| controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise\ | Performs control transfer. | + +## How to Develop You can set a USB device as a host to connect to a device for data transfer. The development procedure is as follows: @@ -211,6 +152,4 @@ You can set a USB device as a host to connect to a device for data transfer. The ```js usb.releaseInterface(pipe, interface); usb.closePipe(pipe); - ``` - - + ``` \ No newline at end of file diff --git a/en/application-dev/device/vibrator-guidelines.md b/en/application-dev/device/vibrator-guidelines.md index f0eb8c5f896ae881550aeae85759692fd052c2ce..b8d201c22ed514ca0047b73b50e9f2184cf0587c 100644 --- a/en/application-dev/device/vibrator-guidelines.md +++ b/en/application-dev/device/vibrator-guidelines.md @@ -8,20 +8,20 @@ You can set different vibration effects as needed, for example, customizing the ## Available APIs - | Module| API| Description| -| -------- | -------- | -------- | -| ohos.vibrator | vibrate(duration: number): Promise<void> | Triggers vibration with the specified duration. This API uses a promise to return the result.| -| ohos.vibrator | vibrate(duration: number, callback?: AsyncCallback<void>): void | Triggers vibration with the specified duration. This API uses a callback to return the result.| -| ohos.vibrator | vibrate(effectId: EffectId): Promise<void> | Triggers vibration with the specified effect. This API uses a promise to return the result.| -| ohos.vibrator | vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void | Triggers vibration with the specified effect. This API uses a callback to return the result.| -| ohos.vibrator | stop(stopMode: VibratorStopMode): Promise<void> | Stops vibration. This API uses a promise to return the result.| -| ohos.vibrator | stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void | Stops vibration. This API uses a callback to return the result.| +| Module | API | Description | +| ------------- | ---------------------------------------- | ------------------------------- | +| ohos.vibrator | vibrate(duration: number): Promise<void> | Triggers vibration with the specified duration. This API uses a promise to return the result. | +| ohos.vibrator | vibrate(duration: number, callback?: AsyncCallback<void>): void | Triggers vibration with the specified duration. This API uses a callback to return the result. | +| ohos.vibrator | vibrate(effectId: EffectId): Promise<void> | Triggers vibration with the specified effect. This API uses a promise to return the result. | +| ohos.vibrator | vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void | Triggers vibration with the specified effect. This API uses a callback to return the result.| +| ohos.vibrator | stop(stopMode: VibratorStopMode): Promise<void> | Stops vibration. This API uses a promise to return the result. | +| ohos.vibrator | stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void | Stops vibration. This API uses a callback to return the result. | ## How to Develop 1. Declare the permissions required for controlling vibrators on the hardware device in the `config.json` file. - + ``` "reqPermissions": [ { @@ -58,7 +58,7 @@ You can set different vibration effects as needed, for example, customizing the ``` 2. Trigger the device to vibrate. - + ``` import vibrator from "@ohos.vibrator" vibrator.vibrate(1000).then((error)=>{ @@ -71,7 +71,7 @@ You can set different vibration effects as needed, for example, customizing the ``` 3. Stop the vibration. - + ``` import vibrator from "@ohos.vibrator" vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error)=>{ diff --git a/en/application-dev/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md index b4d267de31436a70061f5f97e4bbd9b739006328..ee553b735fb510d78ee6531e0a8a71fa99fc53bb 100644 --- a/en/application-dev/dfx/hiappevent-guidelines.md +++ b/en/application-dev/dfx/hiappevent-guidelines.md @@ -15,7 +15,7 @@ JS application event logging APIs are provided by the **hiAppEvent** module. | write(string eventName, EventType type, object keyValues, AsyncCallback\ callback): void | void | Logs application events in asynchronous mode. This method uses an asynchronous callback to return the result. | | write(string eventName, EventType type, object keyValues): Promise\ | Promise\ | Logs application events in asynchronous mode. This method uses a promise to return the result. | -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](hiappevent-overview.md#Event Verification Result Codes). +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** @@ -23,6 +23,24 @@ When an asynchronous callback is used, the return value can be processed directl | ------------------------------ | ------------ | ------------------------------------------------------------ | | configure(ConfigOption config) | boolean | Sets the configuration options for application event logging.
The value **true** indicates that the operation is successful, and value **false** indicates the opposite. | +## Event Verification Result Codes + +| Result Code | Cause | Check Rule | Processing Method | +| ----------- | ---------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| 0 | None | Event verification is successful. | Event logging is normal. No action is required. | +| -1 | Invalid event name | The event name is not empty and contains a maximum of 48 characters.
The event name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore (\_).
The event name does not start with a digit or underscore (_). | Ignore this event and do not perform logging. | +| -2 | Invalid event parameter type | The event name must be a string.
The event type must be a number.
The key value must be an object. | Ignore this event and do not perform logging. | +| -99 | Application event logging disabled | The application event logging function is disabled. | Ignore this event and do not perform logging. | +| -100 | Unknown error | None | Ignore this event and do not perform logging. | +| 1 | Invalid key name | The key name is not empty and contains a maximum of 16 characters.
The key name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore (\_).
The key name does not start with a digit or underscore (\_).
The key name does not end with an underscore (_). | Ignore the key-value pair and continue to perform logging. | +| 2 | Invalid key type | The key must be a string. | Ignore the key-value pair and continue to perform logging. | +| 3 | Invalid value type | The supported value types vary depending on the programming language:
boolean, number, string, or Array [basic element] | Ignore the key-value pair and continue to perform logging. | +| 4 | Value too long | The value can contain a maximum of 8*1024 characters. | Ignore the key-value pair and continue to perform logging. | +| 5 | Excess key-value pairs | The number of key-value pairs must be less than or equal to 32. | Ignore the excess key-value pairs and continue to perform logging. | +| 6 | Excess elements in a list value | The number of elements in a list value must be less than or equal to 100. | Truncate the list with only the first 100 elements retained, and continue to perform logging. | +| 7 | Invalid list value | A list value can only be a basic element.
The elements in a list value must be of the same type. | Ignore the key-value pair and continue to perform logging. | + + ## How to Develop In this example, an application event is logged after the application startup execution page is loaded. diff --git a/en/application-dev/dfx/hiappevent-overview.md b/en/application-dev/dfx/hiappevent-overview.md index a123c647e36d943de41b5878d07c06df0324e386..403aec02035c965da4633e8667be6803031ddf60 100644 --- a/en/application-dev/dfx/hiappevent-overview.md +++ b/en/application-dev/dfx/hiappevent-overview.md @@ -7,20 +7,3 @@ HiAppEvent provides event logging APIs for applications to log the fault, statis 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**: Logs changes caused by user operations to provide service data for development, product, and O&M analysis. - -## Event Verification Result Codes - -| Result Code | Cause | Check Rule | Processing Method | -| ----------- | ---------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| 0 | None | Event verification is successful. | Event logging is normal. No action is required. | -| -1 | Invalid event name | The event name is not empty and contains a maximum of 48 characters.
The event name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore (\_).
The event name does not start with a digit or underscore (_). | Ignore this event and do not perform logging. | -| -2 | Invalid event parameter type | The event name must be a string.
The event type must be a number.
The key value must be an object. | Ignore this event and do not perform logging. | -| -99 | Application event logging disabled | The application event logging function is disabled. | Ignore this event and do not perform logging. | -| -100 | Unknown error | None | Ignore this event and do not perform logging. | -| 1 | Invalid key name | The key name is not empty and contains a maximum of 16 characters.
The key name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore (\_).
The key name does not start with a digit or underscore (\_).
The key name does not end with an underscore (_). | Ignore the key-value pair and continue to perform logging. | -| 2 | Invalid key type | The key must be a string. | Ignore the key-value pair and continue to perform logging. | -| 3 | Invalid value type | The supported value types vary depending on the programming language:
boolean, number, string, or Array [basic element] | Ignore the key-value pair and continue to perform logging. | -| 4 | Value too long | The value can contain a maximum of 8*1024 characters. | Ignore the key-value pair and continue to perform logging. | -| 5 | Excess key-value pairs | The number of key-value pairs must be less than or equal to 32. | Ignore the excess key-value pairs and continue to perform logging. | -| 6 | Excess elements in a list value | The number of elements in a list value must be less than or equal to 100. | Truncate the list with only the first 100 elements retained, and continue to perform logging. | -| 7 | Invalid list value | A list value can only be a basic element.
The elements in a list value must be of the same type. | Ignore the key-value pair and continue to perform logging. | \ No newline at end of file diff --git a/en/application-dev/media/audio-capturer.md b/en/application-dev/media/audio-capturer.md index 00ff76707d2e8d6a2d0ee7dee92fbe8ff92adc84..ab1664eb718591f8abdcd691f1b9ff37b2f97a14 100644 --- a/en/application-dev/media/audio-capturer.md +++ b/en/application-dev/media/audio-capturer.md @@ -1,152 +1,152 @@ # Audio Capture Development ---- -## ***Note***: - 1. This document applies to JavaScript. ---- -## **Summary** -This guide will show how a JS application can use AudioCapturer to record the audio. -Applications can use the APIs provided in this document to record raw audio files. - -## **AudioCapturer Framework** -The AudioCapturer interface is one of the most important components of the audio framework. -### **Audio Capturing:** -The AudioCapturer framework provides APIs for capturing raw audio files. - -## **Usage** -Here's an example of how to use AudioCapturer to capture a raw audio file. -1. Use **createAudioCapturer()** to create an AudioCapturer instance. Capturer parameters can be set in **audioCapturerOptions**.\ - This instance can be used to record, control, and obtain the recording status, as well as to register a callback for notifications. - ``` - var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } - - var audioCapturerInfo = { - source: audio.SourceType.SOURCE_TYPE_MIC, - capturerFlags: 1 - } - - var audioCapturerOptions = { - streamInfo: audioStreamInfo, - capturerInfo: audioCapturerInfo - } - - let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); - var state = audioRenderer.state; - ``` +## When to Use + +You can use the APIs provided by **AudioCapturer** to record raw audio files. + +### State Check + +During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioCapturer** instance. This is because some operations can be performed only when the audio capturer is in a given state. If the application performs an operation when the audio capturer is not in the given state, the system may throw an exception or generate other undefined behavior. + +For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md). + +**Figure 1** Audio capturer state + +![](figures/audio-capturer-state.png) + +## How to Develop + +1. Use **createAudioCapturer()** to create an **AudioCapturer** instance. + + Set parameters of the **AudioCapturer** instance in **audioCapturerOptions**. This instance is used to capture audio, control and obtain the recording status, and register a callback for notification. -2. (Optional) Subscribe to audio capturer state change events using the **on('stateChange')** API. - If an application wants to take some action based on the state updates in capturer, the application can subscribe to the state change event. - There are more events that applications can subscribe to, such as 'markReach' and 'periodReach'. Refer to [Audio](../reference/apis/js-apis-audio.md) for more details. + ```js + var audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + + var audioCapturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 1 + } + + var audioCapturerOptions = { + streamInfo: audioStreamInfo, + capturerInfo: audioCapturerInfo + } + + let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); + var state = audioRenderer.state; ``` + +2. (Optional) Use **on('stateChange')** to subscribe to audio renderer state changes. +If an application needs to perform some operations when the audio renderer state is updated, the application can subscribe to the state changes. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md). + + ```js audioCapturer.on('stateChange',(state) => { console.info('AudioCapturerLog: Changed State to : ' + state) switch (state) { - case audio.AudioState.STATE_PREPARED: - console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); - console.info('Audio State is : Prepared'); - break; - case audio.AudioState.STATE_RUNNING: - console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); - console.info('Audio State is : Running'); - break; - case audio.AudioState.STATE_STOPPED: - console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); - console.info('Audio State is : stopped'); - break; - case audio.AudioState.STATE_RELEASED: - console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); - console.info('Audio State is : released'); - break; - default: - console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); - console.info('Audio State is : invalid'); - break; - } + case audio.AudioState.STATE_PREPARED: + console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); + console.info('Audio State is : Prepared'); + break; + case audio.AudioState.STATE_RUNNING: + console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); + console.info('Audio State is : Running'); + break; + case audio.AudioState.STATE_STOPPED: + console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); + console.info('Audio State is : stopped'); + break; + case audio.AudioState.STATE_RELEASED: + console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); + console.info('Audio State is : released'); + break; + default: + console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); + console.info('Audio State is : invalid'); + break; + } }); - ``` -3. Call the **start()** function on the AudioCapturer instance to start/resume the recording task.\ - The capturer state will be STATE_RUNNING once the start is complete. The application can then begin reading buffers. - ``` - await audioCapturer.start(); - if (audioCapturer.state == audio.AudioState.STATE_RUNNING) { - console.info('AudioRecLog: Capturer started'); - } else { - console.info('AudioRecLog: Capturer start failed'); - } +3. Use **start()** to start audio recording. - ``` + The capturer state will be **STATE_RUNNING** once the audio capturer is started. The application can then begin reading buffers. -4. Obtain the minimum buffer size to read using the **getBufferSize()** API. + ```js + await audioCapturer.start(); + if (audioCapturer.state == audio.AudioState.STATE_RUNNING) { + console.info('AudioRecLog: Capturer started'); + } else { + console.info('AudioRecLog: Capturer start failed'); + } ``` - var bufferSize = await audioCapturer.getBufferSize(); - console.info('AudioRecLog: buffer size: ' + bufferSize); - ``` +4. Use **getBufferSize()** to obtain the minimum buffer size to read. -5. Read the captured audio data and convert it to a byte stream. Call the **read()** API repeatedly to read the data - until the application wants to stop the recording. The following example shows how to write recorded data into a file. + ```js + var bufferSize = await audioCapturer.getBufferSize(); + console.info('AudioRecLog: buffer size: ' + bufferSize); ``` - import fileio from '@ohos.fileio'; - - const path = '/data/data/.pulse_dir/capture_js.wav'; - let fd = fileio.openSync(path, 0o102, 0o777); - if (fd !== null) { - console.info('AudioRecLog: file fd created'); - } - else{ - console.info('AudioRecLog: file fd create : FAILED'); - return; - } - - fd = fileio.openSync(path, 0o2002, 0o666); - if (fd !== null) { - console.info('AudioRecLog: file fd opened in append mode'); - } - - var numBuffersToCapture = 150; - while (numBuffersToCapture) { - var buffer = await audioCapturer.read(bufferSize, true); - if (typeof(buffer) == undefined) { - console.info('read buffer failed'); - } else { - var number = fileio.writeSync(fd, buffer); - console.info('AudioRecLog: data written: ' + number); - } - - numBuffersToCapture--; - } - ``` -6. Once the recording is complete, call the **stop()** API on the AudioCapturer instance to stop the recording. - ``` - await audioCapturer.stop(); - if (audioCapturer.state == audio.AudioState.STATE_STOPPED) { - console.info('AudioRecLog: Capturer stopped'); - } else { - console.info('AudioRecLog: Capturer stop failed'); - } + +5. Read the captured audio data and convert it to a byte stream. Call **read()** repeatedly to read the data until the application wants to stop the recording. + + The following example shows how to write recorded data into a file. + + ```js + import fileio from '@ohos.fileio'; + + const path = '/data/data/.pulse_dir/capture_js.wav'; + let fd = fileio.openSync(path, 0o102, 0o777); + if (fd !== null) { + console.info('AudioRecLog: file fd created'); + } + else{ + console.info('AudioRecLog: file fd create : FAILED'); + return; + } + + fd = fileio.openSync(path, 0o2002, 0o666); + if (fd !== null) { + console.info('AudioRecLog: file fd opened in append mode'); + } + + var numBuffersToCapture = 150; + while (numBuffersToCapture) { + var buffer = await audioCapturer.read(bufferSize, true); + if (typeof(buffer) == undefined) { + console.info('read buffer failed'); + } else { + var number = fileio.writeSync(fd, buffer); + console.info('AudioRecLog: data written: ' + number); + } + + numBuffersToCapture--; + } ``` -7. After the recording task is complete, call the **release()** API on the AudioCapturer instance to release the stream resources. +6. Once the recording is complete, call **stop()** to stop the recording. + ``` - await audioCapturer.release(); - if (audioCapturer.state == audio.AudioState.STATE_RELEASED) { - console.info('AudioRecLog: Capturer released'); - } else { - console.info('AudioRecLog: Capturer release failed'); - } + await audioCapturer.stop(); + if (audioCapturer.state == audio.AudioState.STATE_STOPPED) { + console.info('AudioRecLog: Capturer stopped'); + } else { + console.info('AudioRecLog: Capturer stop failed'); + } ``` -## **Importance of State Check** -Application developers should keep in mind that an AudioCapturer is state-based. -That is, the AudioCapturer has an internal state that the application must always check when calling recorder control APIs, because some operations are only acceptable while the capturer is in a given state.\ -The system may throw an error/exception or generate other undefined behaviour if the application performs an operation while capturer is in an improper state. +7. After the task is complete, call **release()** to release related resources. -## **Other APIs** -See [AudioCapturer in the Audio API](../reference/apis/js-apis-audio.md) for more useful APIs like **getAudioTime**, **getCapturerInfo** and **getStreamInfo**. + ```js + await audioCapturer.release(); + if (audioCapturer.state == audio.AudioState.STATE_RELEASED) { + console.info('AudioRecLog: Capturer released'); + } else { + console.info('AudioRecLog: Capturer release failed'); + } + ``` diff --git a/en/application-dev/media/audio-playback.md b/en/application-dev/media/audio-playback.md index c8dabdf0bea89476f3ff9d81392d2d0d1ee4dc28..cabf6a85c3638656585ff7e315701408c12467bc 100644 --- a/en/application-dev/media/audio-playback.md +++ b/en/application-dev/media/audio-playback.md @@ -256,7 +256,8 @@ export class AudioDemo { The following samples are provided to help you better understand how to develop audio playback: -- [JsDistributedMusicPlayer: Distributed Music Player (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/ability/JsDistributedMusicPlayer) -- [JsAudioPlayer: Audio Playback and Management (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer) -- [eTsAudioPlayer: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets) +- [`JsDistributedMusicPlayer`: Distributed Music Player (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/ability/JsDistributedMusicPlayer) +- [`JsAudioPlayer`: Audio Playback and Management (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer) +- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets) - [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS) + diff --git a/en/application-dev/media/audio-recorder.md b/en/application-dev/media/audio-recorder.md index d24ee72f4a322e44734a0eb7a70ca04d11dc8994..fa43dff19c7488520dd459d53ae326739cdb0fef 100644 --- a/en/application-dev/media/audio-recorder.md +++ b/en/application-dev/media/audio-recorder.md @@ -190,7 +190,8 @@ export class AudioRecorderDemo { The following samples are provided to help you better understand how to develop audio recording: -- [Recorder: Recorder (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder) -- [JsRecorder: Recorder (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/JSRecorder) -- [eTsAudioPlayer: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets) +- [`Recorder`: Recorder (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder) +- [`JsRecorder`: Recorder (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/JSRecorder) +- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets) - [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS) + diff --git a/en/application-dev/media/audio-renderer.md b/en/application-dev/media/audio-renderer.md index f9dfb75c2a08d6c8d641bbe0c8e7960efc6bc6ee..8e2be849396373aaa68ee7c4eb5e36a4cad28c1c 100644 --- a/en/application-dev/media/audio-renderer.md +++ b/en/application-dev/media/audio-renderer.md @@ -1,152 +1,124 @@ # Audio Rendering Development ---- -## ***Note***: - 1. This document applies to JavaScript. ---- -## **Summary** -This guide will show you how to use AudioRenderer to create an audio player app. -You can use the APIs provided in this document to play audio files in output devices and manage playback tasks. +## When to Use -## **AudioRenderer Framework** -The AudioRenderer interface is one of the most important components of the audio framework. -### **Audio Rendering:** -The AudioRenderer framework provides APIs for playing audio files and controlling the playback. -### **Audio Interruption:** -When a higher priority stream wants to play, the AudioRenderer framework interrupts the lower priority stream.\ -For example, if a call is arrived when you listen to music, the music playback, which is the lower priority stream, is paused.\ -With the sample code below, we'll look at how AudioInterrupt works in detail.\ -
-Please see [AudioRenderer in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8) for a list of supported audio stream types and formats, such as AudioSampleFormat, AudioChannel, AudioSampleFormat, and AudioEncodingType. +**AudioRenderer** provides APIs for rendering audio files and controlling playback. It also supports audio interruption. You can use the APIs provided by **AudioRenderer** to play audio files in output devices and manage playback tasks. +### Audio Interruption -## **Usage** -Here's an example of how to use AudioRenderer to play a raw audio file. -1. Use **createAudioRenderer** to create an AudioRenderer instance. Renderer parameters can be set in **audioRendererOptions**.\ - This object can be used to play, control, and obtain the status of the playback, as well as receive callback notifications. - ``` +When an audio stream with a higher priority needs to be played, the audio renderer interrupts the stream with a lower priority. For example, if a call comes in when the user is listening to music, the music playback, which is the lower priority stream, is paused. For details, see [How to Develop](#how-to-develop). + +### State Check + +During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioRenderer** instance. This is because some operations can be performed only when the audio renderer is in a given state. If the application performs an operation when the audio renderer is not in the given state, the system may throw an exception or generate other undefined behavior. + +**Figure 1** Audio renderer state + +![](figures/audio-renderer-state.png) + +### Asynchronous Operations + +To ensure that the UI thread is not blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). + + + +## How to Develop + +1. Use **createAudioRenderer()** to create an **AudioRenderer** instance. + Set parameters of the audio renderer in **audioCapturerOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification. + + ```js var audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, 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 } - + let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); ``` -2. Subscribe to audio interruption events using the **on** API.\ - Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device.\ - In some cases, the framework takes forced actions like pausing and ducking, and notifies the app using **InterruptEvent**. In other cases, the app can take action. In this situation, the app can choose to act on the **InterruptEvent** or ignore it. When the app is interrupted by forced action, it should handle the state, update the user interface, and so on. - - In case of audio interrupts, the app may encounter write failures. Interrupt unaware apps can check the renderer state using the **audioRenderer.state** API before writing audio data, whereas interrupt aware apps will have more details accessible via this listener.\ -
- The following information will be provided by the Interrupt Event Notification: - - 1) **eventType:** Whether the interruption has begun or ended. - - | Value | Description | - | :------------------- | :-------------------------------------------- | - | INTERRUPT_TYPE_BEGIN | Indicates that the interruption has started. | - | INTERRUPT_TYPE_END | Indicates that the interruption has finished. | - - 2) **forceType:** Whether the framework has already taken action or if the app is being suggested to take action. - - | Value | Description | - | :-------------- | :------------------------------------------------------------------ | - | INTERRUPT_FORCE | The audio state has been changed by the framework. | - | INTERRUPT_SHARE | The app can decide whether or not to respond to the InterruptEvent. | - - 3) **hintType:** The kind of action taken or to be taken. - - | Value | Description | - | :-------------------- | :--------------------------- | - | INTERRUPT_HINT_PAUSE | Pausing the playback. | - | INTERRUPT_HINT_RESUME | Resuming the playback. | - | INTERRUPT_HINT_STOP | Stopping the playback. | - | INTERRUPT_HINT_DUCK | Ducking the stream volume. | - | INTERRUPT_HINT_UNDUCK | Unducking the stream volume. | - - 4) **Some actions are exclusively forced or shared**, which means that they are performed by either the framework or the app.\ - For instance, when a call is received while a music stream is ongoing, the framework forces the music stream to pause. When the call is finished, the framework will not forcibly resume the music stream. Instead, it will alert the app to resume the playback. - - | Action | Description | - | :-------------------- | :-------------------------------------------------------------------------------- | - | INTERRUPT_HINT_RESUME | INTERRUPT_SHARE is always the forceType. It can only be done by the app. | - | INTERRUPT_HINT_DUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. | - | INTERRUPT_HINT_UNDUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. | - +2. Use **on('interrupt')** to subscribe to audio interruption events. + + Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device. + + In some cases, the audio renderer performs forcible operations such as pausing and ducking, and notifies the application through **InterruptEvent**. In other cases, the application can choose to act on the **InterruptEvent** or ignore it. + + In the case of audio interruption, the application may encounter write failures. To avoid such failures, interruption unaware applications can use **audioRenderer.state** to check the renderer state before writing audio data. The applications can obtain more details by subscribing to the audio interruption events. For details, see [InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9). + + ```js + audioRenderer.on('interrupt', (interruptEvent) => { + console.info('InterruptEvent Received'); + console.info('InterruptType: ' + interruptEvent.eventType); + console.info('InterruptForceType: ' + interruptEvent.forceType); + console.info('AInterruptHint: ' + interruptEvent.hintType); + + if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { + switch (interruptEvent.hintType) { + // Force Pause: Action was taken by framework. + // Halt the write calls to avoid data loss. + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + isPlay = false; + break; + // Force Stop: Action was taken by framework. + // Halt the write calls to avoid data loss. + case audio.InterruptHint.INTERRUPT_HINT_STOP: + isPlay = false; + break; + // Force Duck: Action was taken by framework, + // just notifying the app that volume has been reduced. + case audio.InterruptHint.INTERRUPT_HINT_DUCK: + break; + // Force Unduck: Action was taken by framework, + // just notifying the app that volume has been restored. + case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: + break; + } + } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { + switch (interruptEvent.hintType) { + // Share Resume: Action is to be taken by App. + // Resume the force paused stream if required. + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + startRenderer(); + break; + // Share Pause: Stream has been interrupted, + // It can choose to pause or play concurrently. + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + isPlay = false; + pauseRenderer(); + break; + } + } + }); ``` - audioRenderer.on('interrupt', (interruptEvent) => { - console.info('InterruptEvent Received'); - console.info('InterruptType: ' + interruptEvent.eventType); - console.info('InterruptForceType: ' + interruptEvent.forceType); - console.info('AInterruptHint: ' + interruptEvent.hintType); - if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { - switch (interruptEvent.hintType) { - // Force Pause: Action was taken by framework. - // Halt the write calls to avoid data loss. - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - isPlay = false; - break; - // Force Stop: Action was taken by framework. - // Halt the write calls to avoid data loss. - case audio.InterruptHint.INTERRUPT_HINT_STOP: - isPlay = false; - break; - // Force Duck: Action was taken by framework, - // just notifying the app that volume has been reduced. - case audio.InterruptHint.INTERRUPT_HINT_DUCK: - break; - // Force Unduck: Action was taken by framework, - // just notifying the app that volume has been restored. - case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: - break; - } - } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { - switch (interruptEvent.hintType) { - // Share Resume: Action is to be taken by App. - // Resume the force paused stream if required. - case audio.InterruptHint.INTERRUPT_HINT_RESUME: - startRenderer(); - break; - // Share Pause: Stream has been interrupted, - // It can choose to pause or play concurrently. - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - isPlay = false; - pauseRenderer(); - break; - } - } - }); - ``` +3. Use **start()** to start audio rendering. + + The renderer state will be **STATE_RUNNING** once the audio renderer is started. The application can then begin reading buffers. -4. Call the **start()** function on the AudioRenderer instance to start/resume the playback task.\ - The renderer state will be STATE_RUNNING once the start is complete. You can then begin writing buffers. - ``` + ```js async function startRenderer() { var state = audioRenderer.state; - // state should be prepared, paused or stopped. + // The state should be prepared, paused, or stopped. if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || state != audio.AudioState.STATE_STOPPED) { console.info('Renderer is not in a correct state to start'); return; } - + await audioRenderer.start(); - + state = audioRenderer.state; if (state == audio.AudioState.STATE_RUNNING) { console.info('Renderer started'); @@ -154,11 +126,13 @@ Here's an example of how to use AudioRenderer to play a raw audio file. console.error('Renderer start failed'); } } - - ``` -5. Make **write** calls to start rendering the buffers. - Read the audio data to be played into a buffer. Call the write function repeatedly to write data. ``` + +4. Call **write()** to write data to the buffer. + + Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer. + + ```js async function writeBuffer(buf) { var state = audioRenderer.state; if (state != audio.AudioState.STATE_RUNNING) { @@ -167,13 +141,13 @@ Here's an example of how to use AudioRenderer to play a raw audio file. return; } let writtenbytes = await audioRenderer.write(buf); - + console.info('Actual written bytes: ' + writtenbytes); if (writtenbytes < 0) { console.error('Write buffer failed. check the state of renderer'); } } - + // Reasonable minimum buffer size for renderer. However, the renderer can accept other read sizes as well. const bufferSize = await audioRenderer.getBufferSize(); const path = '/data/file_example_WAV_2MG.wav'; @@ -183,7 +157,7 @@ Here's an example of how to use AudioRenderer to play a raw audio file. let discardHeader = new ArrayBuffer(44); ss.readSync(discardHeader); rlen += 44; - + var id = setInterval(() => { if (isPlay || isRelease) { if (rlen >= totalSize || isRelease) { @@ -201,74 +175,65 @@ Here's an example of how to use AudioRenderer to play a raw audio file. } , 30); // interval to be set based on audio file format ``` -6. (Optional) Call the **pause()** or **stop()** function on the AudioRenderer instance. -``` - async function pauseRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING) { - console.info('Renderer is not running'); - return; - } - - await audioRenderer.pause(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_PAUSED) { - console.info('Renderer paused'); - } else { - console.error('Renderer pause failed'); - } - } - - async function stopRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) { - console.info('Renderer is not running or paused'); - return; - } - - await audioRenderer.stop(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_STOPPED) { - console.info('Renderer stopped'); - } else { - console.error('Renderer stop failed'); - } -} -``` - -7. After the playback task is complete, call the **release()** function on the AudioRenderer instance to release resources.\ - AudioRenderer can use a lot of system resources. As a result, whenever the resources are no longer required, they must be released. To ensure that any system resources allocated to it are appropriately released, you should always call **release()**. -``` - async function releaseRenderer() { - if (state_ == RELEASED || state_ == NEW) { - console.info('Resourced already released'); - return; - } - - await audioRenderer.release(); - - state = audioRenderer.state; - if (state == STATE_RELEASED) { - console.info('Renderer released'); - } else { - console.info('Renderer release failed'); - } - - } -``` - -## **Importance of State Check:** -You should also keep in mind that an AudioRenderer is state-based. -That is, the AudioRenderer has an internal state that you must always check when calling playback control APIs, because some operations are only acceptable while the renderer is in a given state.\ -The system may throw an error/exception or generate other undefined behaviour if you perform an operation while in the improper state.\ +5. (Optional) Call **pause()** or **stop()** to pause or stop rendering. + + ```js + async function pauseRenderer() { + var state = audioRenderer.state; + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; + } + + await audioRenderer.pause(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_PAUSED) { + console.info('Renderer paused'); + } else { + console.error('Renderer pause failed'); + } + } + + async function stopRenderer() { + var state = audioRenderer.state; + if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) { + console.info('Renderer is not running or paused'); + return; + } + + await audioRenderer.stop(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_STOPPED) { + console.info('Renderer stopped'); + } else { + console.error('Renderer stop failed'); + } + } + ``` -## **Asynchronous Operations:** -Most of the AudioRenderer calls are asynchronous. As a result, the UI thread will not be blocked.\ -For each API, the framework provides both callback and promises functions.\ -In the example, promise functions are used for simplicity. [AudioRender in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8) -provides reference for both callback and promise. +6. After the task is complete, call **release()** to release related resources. + + **AudioRenderer** uses a large number of system resources. Therefore, ensure that the resources are released after the task is complete. + + ```js + async function releaseRenderer() { + if (state_ == RELEASED || state_ == NEW) { + console.info('Resourced already released'); + return; + } + + await audioRenderer.release(); + + state = audioRenderer.state; + if (state == STATE_RELEASED) { + console.info('Renderer released'); + } else { + console.info('Renderer release failed'); + } + + } + ``` -## **Other APIs:** -See [Audio](../reference/apis/js-apis-audio.md) for more useful APIs like getAudioTime, drain, and getBufferSize. + diff --git a/en/application-dev/media/figures/audio-capturer-state.png b/en/application-dev/media/figures/audio-capturer-state.png new file mode 100644 index 0000000000000000000000000000000000000000..52b5556260dbf78c5e816b37013248a07e8dbbc6 Binary files /dev/null and b/en/application-dev/media/figures/audio-capturer-state.png differ diff --git a/en/application-dev/media/figures/audio-renderer-state.png b/en/application-dev/media/figures/audio-renderer-state.png new file mode 100644 index 0000000000000000000000000000000000000000..9ae30c2a9306dc85662405c36da9e11d07ed9a2a Binary files /dev/null and b/en/application-dev/media/figures/audio-renderer-state.png differ diff --git a/en/application-dev/napi/Readme-EN.md b/en/application-dev/napi/Readme-EN.md index 33670e46af96c2bb35b120bd4be23958bce8f84b..9ab337ed1c29e18772ff4e348c47e3202f74815f 100644 --- a/en/application-dev/napi/Readme-EN.md +++ b/en/application-dev/napi/Readme-EN.md @@ -1,3 +1,6 @@ # Native APIs - [Using Native APIs in Application Projects](napi-guidelines.md) +- [Drawing Development](drawing-guidelines.md) +- [Raw File Development](rawfile-guidelines.md) + diff --git a/en/application-dev/napi/drawing-guidelines.md b/en/application-dev/napi/drawing-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..e813f84d92d4155e78c9ca651af6a3e3cd010232 --- /dev/null +++ b/en/application-dev/napi/drawing-guidelines.md @@ -0,0 +1,208 @@ +# Drawing Development + +## When to Use + +The Native Drawing module provides APIs for drawing 2D graphics and text. The following scenarios are common for drawing development: +* Drawing 2D graphics +* Drawing and painting text + +## Available APIs + +| API| Description| +| -------- | -------- | +| OH_Drawing_BitmapCreate (void) | Creates a bitmap object.| +| OH_Drawing_BitmapBuild (OH_Drawing_Bitmap *, const uint32_t width, const uint32_t height, const OH_Drawing_BitmapFormat *) | Initializes the width and height of a bitmap object and sets the pixel format for the bitmap.| +| OH_Drawing_CanvasCreate (void) | Creates a canvas object.| +| OH_Drawing_CanvasBind (OH_Drawing_Canvas *, OH_Drawing_Bitmap *) | Binds a bitmap to a canvas so that the content drawn on the canvas is output to the bitmap (this process is called CPU rendering).| +| OH_Drawing_CanvasAttachBrush (OH_Drawing_Canvas *, const OH_Drawing_Brush *) | Attaches a brush to a canvas so that the canvas will use the style and color of the brush to fill in a shape.| +| OH_Drawing_CanvasAttachPen (OH_Drawing_Canvas *, const OH_Drawing_Pen *) | Attaches a pen to a canvas so that the canvas will use the style and color of the pen to outline a shape.| +| OH_Drawing_CanvasDrawPath (OH_Drawing_Canvas *, const OH_Drawing_Path *) | Draws a path.| +| OH_Drawing_PathCreate (void) | Creates a path object.| +| OH_Drawing_PathMoveTo (OH_Drawing_Path *, float x, float y) | Sets the start point of a path.| +| OH_Drawing_PathLineTo (OH_Drawing_Path *, float x, float y) | Draws a line segment from the last point of a path to the target point. | +| OH_Drawing_PathClose (OH_Drawing_Path *) | Closes a path. A line segment from the start point to the last point of the path is added.| +| OH_Drawing_PenCreate (void) | Creates a pen object.| +| OH_Drawing_PenSetAntiAlias (OH_Drawing_Pen *, bool) | Checks whether anti-aliasing is enabled for a pen. If anti-aliasing is enabled, edges will be drawn with partial transparency.| +| OH_Drawing_PenSetWidth (OH_Drawing_Pen *, float width) | Sets the thickness for a pen. This thickness determines the width of the outline of a shape.| +| OH_Drawing_BrushCreate (void) | Creates a brush object.| +| OH_Drawing_BrushSetColor (OH_Drawing_Brush *, uint32_t color) | Sets the color for a brush. The color will be used by the brush to fill in a shape.| +| OH_Drawing_CreateTypographyStyle (void) | Creates a `TypographyStyle` object.| +| OH_Drawing_CreateTextStyle (void) | Creates a `TextStyle` object.| +| OH_Drawing_TypographyHandlerAddText (OH_Drawing_TypographyCreate *, const char *) | Sets the text content.| +| OH_Drawing_TypographyPaint (OH_Drawing_Typography *, OH_Drawing_Canvas *, double, double) | Paints text on the canvas.| + + + +## Development Procedure for 2D Graphics Drawing + +The following steps describe how to use the canvas and brush of the Native Drawing module to draw a 2D graphics. + +1. **Create a bitmap object.** Use `OH_Drawing_BitmapCreate` in `drawing_bitmap.h` to create a bitmap object (named `cBitmap` in this example), and use `OH_Drawing_BitmapBuild` to specify its length, width, and pixel format. + + ```c++ + // Create a bitmap object. + OH_Drawing_Bitmap* cBitmap = OH_Drawing_BitmapCreate(); + // Define the pixel format of the bitmap. + OH_Drawing_BitmapFormat cFormat {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUYE}; + // Set the pixel format for the bitmap. + OH_Drawing_BitmapBuild(cBitmap, width, height, &cFormat); + ``` + +2. **Create a canvas object.** Use `OH_Drawing_CanvasCreate` in `drawing_canvas.h` to create a canvas object (named `cCanvas` in this example), and use `OH_Drawing_CanvasBind` to bind `cBitmap` to this canvas. The content drawn on the canvas will be output to the bound `cBitmap` object. + + ```c++ + // Create a canvas object. + OH_Drawing_Canvas* cCanvas = OH_Drawing_CanvasCreate(); + // Bind the bitmap to the canvas. The content drawn on the canvas will be output to the bound bitmap memory. + OH_Drawing_CanvasBind(cCanvas, cBitmap); + // Use white to clear the canvas. + OH_Drawing_CanvasClear(cCanvas, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0xFF, 0xFF)); + ``` + +3. **Construct a shape.** Use the APIs provided in `drawing_path.h` to draw a pentagram `cPath`. + + ```c++ + int len = 300; + + float aX = 500; + float aY = 500; + + float dX = aX - len * std::sin(18.0f); + float dY = aY + len * std::cos(18.0f); + + float cX = aX + len * std::sin(18.0f); + float cY = dY; + + float bX = aX + (len / 2.0); + float bY = aY + std::sqrt((cX - dX) * (cX - dX) + (len / 2.0) * (len / 2.0)); + + float eX = aX - (len / 2.0); + float eY = bY; + + // Create a path object and use the APIs to draw a pentagram. + OH_Drawing_Path* cPath = OH_Drawing_PathCreate(); + // Specify the start point of the path. + OH_Drawing_PathMoveTo(cPath, aX, aY); + // Draw a line segment from the last point of a path to the target point. + OH_Drawing_PathLineTo(cPath, bX, bY); + OH_Drawing_PathLineTo(cPath, cX, cY); + OH_Drawing_PathLineTo(cPath, dX, dY); + OH_Drawing_PathLineTo(cPath, eX, eY); + // Close the path. Now the path is drawn. + OH_Drawing_PathClose(cPath); + ``` + +4. **Set the brush and pen styles.** Use `OH_Drawing_PenCreate` in `drawing_pen.h` to create a pen (named `cPen` in this example), and set the attributes such as the anti-aliasing, color, and thickness. The pen is used to outline a shape. Use `OH_Drawing_BrushCreate` in `drawing_brush.h` to create a brush (named `cBrush` in this example), and set the brush color. The brush is used to fill in a shape. Use `OH_Drawing_CanvasAttachPen` and `OH_Drawing_CanvasAttachBrush` in `drawing_canvas.h` to attach the pen and brush to the canvas. + + ```c++ + // Create a pen object and set the anti-aliasing, color, and thickness. + OH_Drawing_Pen* cPen = OH_Drawing_PenCreate(); + OH_Drawing_PenSetAntiAlias(cPen, true); + OH_Drawing_PenSetColor(cPen, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0x00, 0x00)); + OH_Drawing_PenSetWidth(cPen, 10.0); + OH_Drawing_PenSetJoin(cPen, LINE_ROUND_JOIN); + // Attach the pen to the canvas. + OH_Drawing_CanvasAttachPen(cCanvas, cPen); + + // Create a brush object and set the color. + OH_Drawing_Brush* cBrush = OH_Drawing_BrushCreate(); + OH_Drawing_BrushSetColor(cBrush, OH_Drawing_ColorSetArgb(0xFF, 0x00, 0xFF, 0x00)); + + // Attach the brush to the canvas. + OH_Drawing_CanvasAttachBrush(cCanvas, cBrush); + ``` + +5. **Draw a shape.** Use `OH_Drawing_CanvasDrawPath` in `drawing_canvas.h` to draw a pentagram on the canvas. Call the corresponding APIs to destroy the objects when they are no longer needed. + + ```c++ + // Draw a pentagram on the canvas. The outline of the pentagram is drawn by the pen, and the color is filled in by the brush. + OH_Drawing_CanvasDrawPath(cCanvas, cPath); + // Destroy the created objects when they are no longer needed. + OH_Drawing_BrushDestory(cBrush); + OH_Drawing_PenDestory(cPen); + OH_Drawing_PathDestory(cPath); + ``` + +6. **Obtain pixel data.** Use `OH_Drawing_BitmapGetPixels` in `drawing_bitmap.h` to obtain the pixel address of the bitmap bound to the canvas. The memory to which the address points contains the pixel data of the drawing on the canvas. + + ```c++ + // Obtain the pixel address after drawing. The memory to which the address points contains the pixel data of the drawing on the canvas. + void* bitmapAddr = OH_Drawing_BitmapGetPixels(cBitmap); + auto ret = memcpy_s(addr, addrSize, bitmapAddr, addrSize); + if (ret != EOK) { + LOGI("memcpy_s failed"); + } + // Destroy the canvas object. + OH_Drawing_CanvasDestory(cCanvas); + // Destroy the bitmap object. + OH_Drawing_BitmapDestory(cBitmap); + ``` + +## Development Procedure for Text Drawing and Display + +The following steps describe how to use the text drawing and display feature of the Native Drawing module. +1. **Create a canvas and a bitmap.** + + ```c++ + // Create a bitmap. + OH_Drawing_Bitmap* cBitmap = OH_Drawing_BitmapCreate(); + OH_Drawing_BitmapFormat cFormat {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUE}; + OH_Drawing_BitmapBuild(cBitmap, width, height, &cFormat); + // Create a canvas. + OH_Drawing_Canvas* cCanvas = OH_Drawing_CanvasCreate(); + OH_Drawing_CanvasBind(cCanvas, cBitmap); + OH_Drawing_CanvasClear(cCanvas, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0xFF, 0xFF)); + ``` + +2. **Set the typography style.** + + ```c++ + // Set the typography attributes such as left to right (LTR) for the text direction and left-aligned for the text alignment mode. + OH_Drawing_TypographyStyle* typoStyle = OH_Drawing_CreateTypographyStyle(); + OH_Drawing_SetTypographyTextDirection(typoStyle, TEXT_DIRECTION_LTR); + OH_Drawing_SetTypographyTextAlign(typoStyle, TEXT_ALIGN_LEFT); + ``` + +3. **Set the text style.** + + ```c++ + // Set the text color, for example, black. + OH_Drawing_TextStyle* txtStyle = OH_Drawing_CreateTextStyle(); + OH_Drawing_SetTextStyleColor(txtStyle, OH_Drawing_ColorSetArgb(0xFF, 0x00, 0x00, 0x00)); + // Set text attributes such as the font size and weight. + double fontSize = 30; + OH_Drawing_SetTextStyleFontSize(txtStyle, fontSize); + OH_Drawing_SetTextStyleFontWeight(txtStyle, FONT_WEIGHT_400); + OH_Drawing_SetTextStyleBaseLine(txtStyle, TEXT_BASELINE_ALPHABETIC); + OH_Drawing_SetTextStyleFontHeight(txtStyle, 1); + // Set the font families. + const char* fontFamilies[] = {"Roboto"}; + OH_Drawing_SetTextStyleFontFamilies(txtStyle, 1, fontFamilies); + OH_Drawing_SetTextStyleFontStyle(txtStyle, FONT_STYLE_NORMAL); + OH_Drawing_SetTextStyleLocale(txtStyle, "en"); + ``` + +4. **Generate the final text display effect.** + + ```c++ + OH_Drawing_TypographyCreate* handler = OH_Drawing_CreateTypographyHandler(typoStyle, + OH_Drawing_CreateFontCollection()); + OH_Drawing_TypographyHandlerPushTextStyle(handler, txtStyle); + // Set the text content. + const char* text = "OpenHarmony\n"; + OH_Drawing_TypographyHandlerAddText(handler, text); + OH_Drawing_TypographyHandlerPopTextStyle(handler); + OH_Drawing_Typography* typography = OH_Drawing_CreateTypography(handler); + // Set the maximum width. + double maxWidth = 800.0; + OH_Drawing_TypographyLayout(typography, maxWidth); + // Set the start position for text display. + double position[2] = {10.0, 15.0}; + OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]); + ``` + +## Samples + +The following samples are provided to help you better understand how to use the Native Drawing module: +* [2D Graphics Drawing Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/2d_graphics/drawing_c_sample.cpp) +* [Text Drawing and Painting Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/text/renderservice/drawing_text_c_sample.cpp) diff --git a/en/application-dev/napi/rawfile-guidelines.md b/en/application-dev/napi/rawfile-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..c585b162a2dc483ca72a5369170b2ee0f43a01a1 --- /dev/null +++ b/en/application-dev/napi/rawfile-guidelines.md @@ -0,0 +1,173 @@ +# Raw File Development + + + +## When to Use + +This document describes how to use the native Rawfile APIs to manage raw file directories and files in OpenHarmony. You can use the APIs to traverse, open, search for, read, and close raw files. + +## Available APIs + +| API | Description | +| :----------------------------------------------------------- | :--------------------------------------- | +| NativeResourceManager *OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr) | Initializes the native resource manager. | +| RawDir *OH_ResourceManager_OpenRawDir(const NativeResourceManager *mgr, const char *dirName) | Opens a raw file directory. | +| int OH_ResourceManager_GetRawFileCount(RawDir *rawDir) | Obtains the number of raw files in the specified directory.| +| const char *OH_ResourceManager_GetRawFileName(RawDir *rawDir, int index) | Obtains the name of a raw file. | +| RawFile *OH_ResourceManager_OpenRawFile(const NativeResourceManager *mgr, const char *fileName) | Opens a raw file. | +| long OH_ResourceManager_GetRawFileSize(RawFile *rawFile) | Obtains the size of a raw file. | +| int OH_ResourceManager_SeekRawFile(const RawFile *rawFile, long offset, int whence) | Seeks a read/write position in a raw file based on the specified offset. | +| long OH_ResourceManager_GetRawFileOffset(const RawFile *rawFile) | Obtains the offset. | +| int OH_ResourceManager_ReadRawFile(const RawFile *rawFile, void *buf, size_t length) | Reads a raw file. | +| void OH_ResourceManager_CloseRawFile(RawFile *rawFile) | Closes a raw file to release resources. | +| void OH_ResourceManager_CloseRawDir(RawDir *rawDir) | Closes a raw file directory to release resources. | +| bool OH_ResourceManager_GetRawFileDescriptor(const RawFile *rawFile, RawFileDescriptor &descriptor) | Obtains the file descriptor (FD) of a raw file. | +| bool OH_ResourceManager_ReleaseRawFileDescriptor(const RawFileDescriptor &descriptor) | Releases the FD of a raw file. | +| void OH_ResourceManager_ReleaseNativeResourceManager(NativeResourceManager *resMgr) | Releases the native resource manager. | + +## How to Develop + +1. Add the header file. + + ```c++ + #include "raw_file_manager.h" + ``` + + + +2. Call **OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr)** to obtain a **NativeResourceManager** instance. + + ```js + // Import the JS resource manager from the JS head file and pass it to the C++ file. + import resManager from '@ohos.resourceManager' + import rawfileTest from 'librawFileTest.so' + resManager.getResourceManager().then(resmgr => { + rawfileTest.testRawFile("test", resmgr, (error, value) => { + console.log("test rawFile"); + }) + }); + ``` + + ```c++ + // Obtain and parse the parameters in the C++ file. + NativeResourceManager* nativeResourceManager = nullptr; + std::string path; + if (i == 0 && valueType == napi_string) { + // Parse the first parameter, which is the file or directory path relative to the raw file directory. + ...... + path = buf.data(); + } else if (i == 1 && valueType == napi_object) { + // Parse the second parameter, which is the JS resource manager. + nativeResourceManager = OH_ResourceManager_InitNativeResourceManager(env, argv[i]); + } + ``` + + + +3. Call **OH_ResourceManager_OpenRawDir** to obtain a **RawDir** instance based on the **NativeResourceManager** instance. + + ```c++ + RawDir* rawDir = OH_ResourceManager_OpenRawDir(nativeResourceManager, path.c_str()); + ``` + + + +4. Call **OH_ResourceManager_GetRawFileCount** to obtain the total number of raw files in the directory based on the **RawDir** instance. + + ```c++ + int count = OH_ResourceManager_GetRawFileCount(rawDir); + ``` + + + +5. Call **OH_ResourceManager_GetRawFileName** to obtain the name of the raw file with the specified index. + + ```c++ + for (int index = 0; index < count; index++) { + std::string fileName = OH_ResourceManager_GetRawFileName(rawDir, index); + } + ``` + + + +6. Call **OH_ResourceManager_OpenRawFile** to obtain a **RawFile** instance with the specified file name. + + ```c++ + RawFile* rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, fileName.c_str()); + ``` + + + +7. Call **OH_ResourceManager_GetRawFileSize** to obtain the size of the raw file. + + ```c++ + long rawFileSize = OH_ResourceManager_GetRawFileSize(rawFile); + ``` + + + +8. Call **OH_ResourceManager_SeekRawFile** to seek a read/write position in the raw file based on the specified offset. + + ```c++ + int position = OH_ResourceManager_SeekRawFile(rawFile, 10, 0); + int position = OH_ResourceManager_SeekRawFile(rawFile, 0 , 1); + int position = OH_ResourceManager_SeekRawFile(rawFile, -10, 2); + ``` + + + +9. Call **OH_ResourceManager_GetRawFileOffset** to obtain the raw file offset. + + ```c++ + long rawFileOffset = OH_ResourceManager_GetRawFileOffset(rawFile) + ``` + + + +10. Call **OH_ResourceManager_ReadRawFile** to read the raw file. + + ```c++ + std::unique_ptr mediaData = std::make_unique(rawFileSize); + long rawFileOffset = OH_ResourceManager_ReadRawFile(rawFile, mediaData.get(), rawFileSize); + ``` + + + +11. Call **OH_ResourceManager_CloseRawFile** to close the file to release resources. + + ```c++ + OH_ResourceManager_CloseRawFile(rawFile); + ``` + + + +12. Call **OH_ResourceManager_CloseRawDir** to close the raw file directory. + + ```c++ + OH_ResourceManager_CloseRawDir(rawDir); + ``` + + + +13. Call **OH_ResourceManager_GetRawFileDescriptor** to obtain the FD of the raw file. + + ```c++ + RawFileDescriptor descriptor; + bool result = OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor); + ``` + + + +14. Call **OH_ResourceManager_ReleaseRawFileDescriptor** to release the FD of the raw file. + + ```c++ + OH_ResourceManager_ReleaseRawFileDescriptor(descriptor); + ``` + + + +15. Call **OH_ResourceManager_ReleaseNativeResourceManager** to release the native resource manager. + + ```c++ + OH_ResourceManager_ReleaseNativeResourceManager(nativeResourceManager); + ``` diff --git a/en/application-dev/notification/assistant-guidelines.md b/en/application-dev/notification/assistant-guidelines.md index 35d3eaeaaddd023861056fe819fbe4016c59bb01..c6de99e3fee6919ef1ca1e1a0f87a7aa0a890a74 100644 --- a/en/application-dev/notification/assistant-guidelines.md +++ b/en/application-dev/notification/assistant-guidelines.md @@ -2,9 +2,9 @@ The common event and notification module provides debugging tools to facilitate your application development. With these tools, you can view common event and notification information, publish common events, and more. These tools have been integrated with the system. You can run related commands directly in the shell. -### cem Debugging Assistant +## cem Debugging Assistant -##### publish +### publish * Functionality @@ -41,7 +41,7 @@ The common event and notification module provides debugging tools to facilitate ![cem-publish-all](figures/cem-publish-all.png) -##### dump +### dump * Functionality @@ -67,7 +67,7 @@ The common event and notification module provides debugging tools to facilitate ​ ![cem-dump-e](figures/cem-dump-e.png) -##### help +### help * Functionality @@ -83,9 +83,9 @@ The common event and notification module provides debugging tools to facilitate -### anm Debugging Assistant +## anm Debugging Assistant -##### dump +### dump * Functionality @@ -119,7 +119,7 @@ The common event and notification module provides debugging tools to facilitate Set the number of the cached recent notifications to be displayed to 10. -##### help +### help * Functionality diff --git a/en/application-dev/notification/common-event.md b/en/application-dev/notification/common-event.md index 8ea3eaa2d6b2f450f28660ca9f50ad3b99947c8b..e48bcd802e2a1d16536c29193748b14193517e4c 100644 --- a/en/application-dev/notification/common-event.md +++ b/en/application-dev/notification/common-event.md @@ -1,5 +1,5 @@ # Common Event Development -### Introduction +## Introduction OpenHarmony provides a Common Event Service (CES) for applications to subscribe to, publish, and unsubscribe from common events. Common events are classified into system common events and custom common events. @@ -25,13 +25,13 @@ You can create a subscriber object to subscribe to a common event to obtain the ### How to Develop 1. Import the **commonEvent** module. -```javascript +```js import commonEvent from '@ohos.commonEvent'; ``` 2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo). -```javascript +```js private subscriber = null // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information @@ -42,7 +42,7 @@ var subscribeInfo = { 3. Create a subscriber object and save the returned object for subsequent operations such as subscription and unsubscription. -```javascript +```js // Callback for subscriber creation. commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => { if (err.code) { @@ -57,7 +57,7 @@ commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => { 4. Create a subscription callback, which is triggered when an event is received. The data returned by the subscription callback contains information such as the common event name and data carried by the publisher. For details about the data types and parameters of the common event data, see [CommonEventData](../reference/apis/js-apis-commonEvent.md#commoneventdata). -```javascript +```js // Callback for common event subscription. if (this.subscriber != null) { commonEvent.subscribe(this.subscriber, (err, data) => { @@ -74,7 +74,7 @@ if (this.subscriber != null) { } ``` -## Public Event Publishing Development +## Common Event Publishing Development ### When to Use You can use the **publish** APIs to publish a custom common event, which can carry data for subscribers to parse and process. @@ -89,13 +89,13 @@ You can use the **publish** APIs to publish a custom common event, which can car #### Development for Publishing a Common Event 1. Import the **commonEvent** module. -```javascript +```js import commonEvent from '@ohos.commonEvent'; ``` 2. Pass in the common event name and callback, and publish the event. -```javascript +```js // Publish a common event. commonEvent.publish("event", (err) => { if (err.code) { @@ -109,13 +109,13 @@ commonEvent.publish("event", (err) => { #### Development for Publishing a Common Event with Given Attributes 1. Import the **commonEvent** module. -```javascript +```js import commonEvent from '@ohos.commonEvent' ``` 2. Define attributes of the common event to publish. For details about the data types and parameters in the data to publish, see [CommonEventPublishData](../reference/apis/js-apis-commonEvent.md#commoneventpublishdata). -```javascript +```js // Attributes of a common event. var options = { code: 1, // Result code of the common event @@ -125,7 +125,7 @@ var options = { 3. Pass in the common event name, attributes of the common event, and callback, and publish the event. -```javascript +```js // Publish a common event. commonEvent.publish("event", options, (err) => { if (err.code) { @@ -149,14 +149,14 @@ You can use the **unsubscribe** API to unsubscribe from a common event. ### How to Develop 1. Import the **commonEvent** module. -```javascript +```js import commonEvent from '@ohos.commonEvent'; ``` 2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#Common-Event-Subscription-Development). 3. Invoke the **unsubscribe** API in **CommonEvent** to unsubscribe from the common event. -```javascript +```js if (this.subscriber != null) { commonEvent.unsubscribe(this.subscriber, (err) => { if (err.code) { diff --git a/en/application-dev/quick-start/figures/image-20220326064841782.png b/en/application-dev/quick-start/figures/image-20220326064841782.png index ce4450151f3dc0de82cd8f57cf6018eebbc46f58..a7811ffe339baceffbfff66f2173b2e5e29a6fc1 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326064841782.png and b/en/application-dev/quick-start/figures/image-20220326064841782.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326064913834.png b/en/application-dev/quick-start/figures/image-20220326064913834.png index c7fb0ea68933a659f81b1febb2ef946c2b274e42..9bb845a90c3b80db95c736cc84d2434537cf8522 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326064913834.png and b/en/application-dev/quick-start/figures/image-20220326064913834.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326064955505.png b/en/application-dev/quick-start/figures/image-20220326064955505.png index bf1180a41e86bbb39c48e7c132f0929e6c448aed..89a43655a064971b721a5aee4222d7c2d37c9523 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326064955505.png and b/en/application-dev/quick-start/figures/image-20220326064955505.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326065043006.png b/en/application-dev/quick-start/figures/image-20220326065043006.png index 2cf4b8a6503e6a7a3d7095d092144927384127f7..c8b11931993c83e507dbf7150a5be740430ae42f 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326065043006.png and b/en/application-dev/quick-start/figures/image-20220326065043006.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326065124911.png b/en/application-dev/quick-start/figures/image-20220326065124911.png index 872f36c3bf328dcb4ff58ac6f9106d5c4726dc56..858a8af31bc83367fc4c2f696d0f69e58b36b216 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326065124911.png and b/en/application-dev/quick-start/figures/image-20220326065124911.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326065201867.png b/en/application-dev/quick-start/figures/image-20220326065201867.png index 5c3b428823d5f044a2857e641ac2465beff39114..e447e34c0a80c472cb2dfd684e1822866b4134d8 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326065201867.png and b/en/application-dev/quick-start/figures/image-20220326065201867.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326072448840.png b/en/application-dev/quick-start/figures/image-20220326072448840.png index dac0f9dfe41d8f7667e21f2224563910e3aa9429..861ef6a871ce38d28a1144722ff4d0d327a8bc84 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326072448840.png and b/en/application-dev/quick-start/figures/image-20220326072448840.png differ diff --git a/en/application-dev/quick-start/start-with-ets-low-code.md b/en/application-dev/quick-start/start-with-ets-low-code.md index d69957f3598f92400aca8968a5571be8caf61f96..ca50b149038b8b5e573039f45bacabfbcaec1ec2 100644 --- a/en/application-dev/quick-start/start-with-ets-low-code.md +++ b/en/application-dev/quick-start/start-with-ets-low-code.md @@ -94,7 +94,8 @@ Add **Column**, **Text**, and **Button** components to the first page. A column 4. Add a **Text** component. - In the **second.ets** file, set the message text content to **Hi there**. The sample code is as follows: - ``` + ```ts + // second.ets @Entry @Component struct Second { @@ -122,7 +123,7 @@ Add **Column**, **Text**, and **Button** components to the first page. A column ## Implementing Page Redirection -You can implement page redirection through the page router, which finds the target page based on the page URI. Import the **router** module and then perform the steps below: +You can implement page redirection through the page router, which finds the target page based on the page URL. Import the **router** module and then perform the steps below: 1. Implement redirection from the first page to the second page. @@ -130,7 +131,8 @@ You can implement page redirection through the page router, which finds the targ - In the **index.ets** file: - ``` + ```ts + // index.ets import router from '@ohos.router'; @Entry @@ -163,7 +165,8 @@ You can implement page redirection through the page router, which finds the targ - In the **second.ets** file: - ``` + ```ts + // second.ets import router from '@ohos.router'; @Entry diff --git a/en/application-dev/quick-start/start-with-ets.md b/en/application-dev/quick-start/start-with-ets.md index 66485cd8aaeada2f1896013c7822aacc30b5872d..443c2b2ce1a6c632008e026b80ec22fb0f20cb79 100644 --- a/en/application-dev/quick-start/start-with-ets.md +++ b/en/application-dev/quick-start/start-with-ets.md @@ -28,7 +28,7 @@ - **src > main > ets > MainAbility > app.ets**: ability lifecycle file. - **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. - **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. - - **build-profile.json5**: current module information and build configuration options, including **buildOption target**. + - **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. - **hvigorfile.js**: module-level compilation and build task script. You can customize related tasks and code implementation. - **build-profile.json5**: application-level configuration information, including the signature and product configuration. - **hvigorfile.js**: application-level compilation and build task script. @@ -41,7 +41,8 @@ After the project synchronization is complete, choose **entry** > **src** > **main** > **ets** > **MainAbility** > **pages** in the **Project** window and open the **index.ets** file. You can see that the file contains a **<Text>** component. The sample code in the **index.ets** file is shown below: - ``` + ```ts + // index.ets @Entry @Component struct Index { @@ -66,7 +67,8 @@ On the default page, add a **<Button>** component to respond to user clicks and implement redirection to another page. The sample code in the **index.ets** file is shown below: - ``` + ```ts + // index.ets @Entry @Component struct Index { @@ -119,7 +121,8 @@ Add **<Text>** and **<Button>** components and set their styles, as you do for the first page. The sample code in the **second.ets** file is shown below: - ``` + ```ts + // second.ets @Entry @Component struct Second { @@ -154,14 +157,15 @@ ## Implementing Page Redirection -You can implement page redirection through the page router, which finds the target page based on the page URI. Import the **router** module and then perform the steps below: +You can implement page redirection through the page router, which finds the target page based on the page URL. Import the **router** module and then perform the steps below: 1. Implement redirection from the first page to the second page. In the **index.ets** file of the first page, bind the **onClick** event to the **Next** button so that clicking the button redirects the user to the second page. The sample code in the **index.ets** file is shown below: - ``` + ```ts + // index.ets import router from '@ohos.router'; @Entry @@ -205,7 +209,8 @@ You can implement page redirection through the page router, which finds the targ In the **second.ets** file of the second page, bind the **onClick** event to the **Back** button so that clicking the button redirects the user back to the first page. The sample code in the **second.ets** file is shown below: - ``` + ```ts + // second.ets import router from '@ohos.router'; @Entry diff --git a/en/application-dev/quick-start/start-with-js-low-code.md b/en/application-dev/quick-start/start-with-js-low-code.md index 69e650671909a57d56c6486346938a4804de2fdf..865f2b69847412f626c47d8228d1a3dc344a3b7a 100644 --- a/en/application-dev/quick-start/start-with-js-low-code.md +++ b/en/application-dev/quick-start/start-with-js-low-code.md @@ -109,7 +109,7 @@ Open the index.visual file, right-click the existing template components on the ## Implementing Page Redirection -You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URI. Import the **router** module and then perform the steps below: +You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URL. Import the **router** module and then perform the steps below: 1. Implement redirection from the first page to the second page. diff --git a/en/application-dev/quick-start/start-with-js.md b/en/application-dev/quick-start/start-with-js.md index 301da91e43a7f751c4e70135acf5fbce64c3eef8..7cfc53af2b98dc01d9b8f6cf240e7a712538a911 100644 --- a/en/application-dev/quick-start/start-with-js.md +++ b/en/application-dev/quick-start/start-with-js.md @@ -27,7 +27,7 @@ - **src > main > js > MainAbility > app.js**: ability lifecycle file. - **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. - **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. - - **build-profile.json5**: current module information and build configuration options, including **buildOption target**. + - **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. - **hvigorfile.js**: module-level compilation and build task script. You can customize related tasks and code implementation. - **build-profile.json5**: application-level configuration information, including the signature and product configuration. - **hvigorfile.js**: application-level compilation and build task script. @@ -40,7 +40,8 @@ After the project synchronization is complete, choose **entry** > **src** > **main** > **js** > **MainAbility** > **pages** > **index** in the **Project** window and open the **index.hml** file. You can see that the file contains a **<Text>** component. The sample code in the **index.hml** file is shown below: - ``` + ```html +
Hello World @@ -53,7 +54,8 @@ On the default page, add an **<input>** component of the button type to respond to user clicks and implement redirection to another page. The sample code in the **index.hml** file is shown below: - ``` + ```html +
Hello World @@ -69,7 +71,7 @@ From the **Project** window, choose **entry** > **src** > **main** > **js** > **MainAbility** > **pages** > **index**, open the **index.css** file, and set the page styles, such as the width, height, font size, and spacing. The sample code in the **index.css** file is shown below: - ``` + ```css .container { display: flex; flex-direction: column; @@ -119,7 +121,8 @@ Add **<Text>** and **<Button>** components and set their styles, as you do for the first page. The sample code in the **second.hml** file is shown below: - ``` + ```html +
Hi there @@ -132,7 +135,7 @@ 3. Set the page style in the **second.css** file. The sample code in the **second.css** file is shown below: - ``` + ```css .container { display: flex; flex-direction: column; @@ -165,14 +168,15 @@ ## Implementing Page Redirection -You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URI. Import the **router** module and then perform the steps below: +You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URL. Import the **router** module and then perform the steps below: 1. Implement redirection from the first page to the second page. In the **index.js** file of the first page, bind the **onclick** method to the button so that clicking the button redirects the user to the second page. The sample code in the **index.js** file is shown below: - ``` + ```js + // index.js import router from '@ohos.router'; export default { @@ -189,7 +193,8 @@ You can implement page redirection through the [page router](../ui/ui-js-buildin In the **second.ets** file of the second page, bind the **back** method to the **Back** button so that clicking the button redirects the user back to the first page. The sample code in the **second.js** file is shown below: - ``` + ```js + // second.js import router from '@ohos.router'; export default { diff --git a/en/application-dev/quick-start/syscap.md b/en/application-dev/quick-start/syscap.md index bd81ff6771735d0cb78be5321269460a7ebd0bd2..e74c958c4df493bd5084ad477b95f78c7893cd48 100644 --- a/en/application-dev/quick-start/syscap.md +++ b/en/application-dev/quick-start/syscap.md @@ -4,26 +4,26 @@ ### System Capabilities and APIs -SysCap is short for System Capability. It refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each system capability corresponds to a set of bound APIs, whose availability depends on the support of the target device. Such a set of APIs can be provided in the IDE for association. +SysCap is short for System Capability. It refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each SysCap corresponds to a set of bound APIs, whose availability depends on the support of the target device. Such a set of APIs are provided in DevEco Studio for association. ![image-20220326064841782](figures/image-20220326064841782.png) -### Supported Capability Set, Associated Capability Set, and Required Capability Set +### Supported SysCap Set, Associated SysCap Set, and Required SysCap Set -The supported capability set, associated capability set, and required capability set are collections of system capabilities. -The supported capability set covers the device capabilities, and the required capability set covers the application capabilities. If the capability set required by application A is a subset of the capability set supported by device N, application A can be distributed to device N for installation and running. Otherwise, application A cannot be distributed. -The associated capability set covers the system capabilities of associated APIs that the IDE offers during application development. +The supported SysCap set, associated SysCap set, and required SysCap set are collections of SysCaps. +The supported SysCap set covers the device capabilities, and the required SysCap set covers the application capabilities. If the SysCap set required by application A is a subset of the SysCap set supported by device N, application A can be distributed to device N for installation and running. Otherwise, application A cannot be distributed. +The associated SysCap set covers the system capabilities of associated APIs that the IDE offers during application development. ![image-20220326064913834](figures/image-20220326064913834.png) -### Devices and Supported Capability Sets +### Devices and Supported SysCap Sets -Each device provides a capability set that matches its hardware capability. -The SDK classifies devices into general devices and custom devices. The general devices' supported capability set is defined by OpenHarmony, and the custom devices' is defined by device vendors. +Each device provides a SysCap set that matches its hardware capability. +The SDK classifies devices into general devices and custom devices. The general devices' supported SysCap set is defined by OpenHarmony, and the custom devices' is defined by device vendors. ![image-20220326064955505](figures/image-20220326064955505.png) @@ -31,7 +31,7 @@ The SDK classifies devices into general devices and custom devices. The general ### Mapping Between Devices and SDK Capabilities -The SDK provides a full set of APIs for the IDE. The IDE identifies the supported capability set based on the devices supported by the project, filters the APIs contained in the capability set, and provides the supported APIs for association (to autocomplete input). +The SDK provides a full set of APIs for the IDE. DevEco Studio identifies the supported SysCap set based on the devices supported by the project, filters the APIs contained in the SysCap set, and provides the supported APIs for association (to autocomplete input). ![image-20220326065043006](figures/image-20220326065043006.png) @@ -49,11 +49,11 @@ Right-click the project directory and choose **Import Product Compatibility ID** -### Configuring the Associated Capability Set and Required Capability Set +### Configuring the Associated SysCap Set and Required SysCap Set -The IDE automatically configures the associated capability set and required capability set based on the settings supported by the created project. You can modify the capability sets when necessary. -You can add APIs to the associated capability set in the IDE by adding system capabilities. However, note that these APIs may not be supported on the device. Therefore, check whether these APIs are supported before using them. -Exercise caution when modifying the required capability set. Incorrect modifications may result in the application being unable to be distributed to the target device. +DevEco Studio automatically configures the associated SysCap set and required SysCap set based on the settings supported by the created project. You can modify these SysCap sets when necessary. +You can add APIs to the associated SysCap set in DevEco Studio by adding system capabilities. However, note that these APIs may not be supported on the device. Therefore, check whether these APIs are supported before using them. +Exercise caution when modifying the required SysCap set. Incorrect modifications may result in the application being unable to be distributed to the target device. ``` /* syscap.json */ @@ -74,15 +74,15 @@ Exercise caution when modifying the required capability set. Incorrect modificat ... ] }, - development: { /* The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated capability set. */ + development: { /* The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated SysCap set. */ addedSysCaps: [ "SystemCapability.Location.Location.Lite", ... ] }, production: { /* Used to generate the RPCID. Exercise caution when adding this parameter. Under incorrect settings, applications may fail to be distributed to target devices. */ - addedSysCaps: [], // Intersection of SysCap sets supported by devices configured in devices. It is the required capability set with addedSysCaps set and removedSysCaps set. - removedSysCaps: [] // When the required capability set is a capability subset of a device, the application can be distributed to the device. + addedSysCaps: [], // Intersection of SysCap sets supported by devices configured in devices. It is the required SysCap set with addedSysCaps set and removedSysCaps set. + removedSysCaps: [] // When the required SysCap set is a capability subset of a device, the application can be distributed to the device. } } ``` @@ -91,7 +91,7 @@ Exercise caution when modifying the required capability set. Incorrect modificat ### Single-Device Application Development -By default, the associated capability set and required system capability set of the application are the same as the supported system capability set of the device. Exercise caution when modifying the required capability set. +By default, the associated SysCap set and required SysCap set of the application are the same as the supported SysCap set of the device. Exercise caution when modifying the required SysCap set. ![image-20220326065124911](figures/image-20220326065124911.png) @@ -99,7 +99,7 @@ By default, the associated capability set and required system capability set of ### Cross-Device Application Development -By default, the associated capability set of an application is the union of multiple devices' supported capability sets, while the required capability set is the intersection of the devices' supported capability sets. +By default, the associated SysCap set of an application is the union of multiple devices' supported SysCap sets, while the required SysCap set is the intersection of the devices' supported SysCap sets. ![image-20220326065201867](figures/image-20220326065201867.png) @@ -133,9 +133,9 @@ if (geolocation) { -### Checking the Differences Between Devices with the Same Capability +### Checking the Differences Between Devices with a Specific SysCap -The performance of a system capability may vary by device type. For example, a tablet is superior to a smart wearable device in terms of the camera capability. +The performance of a SysCap may vary by device type. For example, a tablet is superior to a smart wearable device in terms of the camera capability. ``` import userAuth from '@ohos.userIAM.userAuth'; @@ -162,7 +162,7 @@ The device SysCaps in product solutions vary according to the component combinat ![image-20220326072448840](figures/image-20220326072448840.png) -1. A set of OpenHarmony source code consists of optional and mandatory components. Different components have different system capabilities. In other words, different components represent different SysCaps. +1. A set of OpenHarmony source code consists of optional and mandatory components. Different components represent different SysCaps. 2. In a normalized released SDK, APIs are mapped to SysCap sets. @@ -170,10 +170,10 @@ The device SysCaps in product solutions vary according to the component combinat 4. The components configured for a product can be OpenHarmony components or proprietary components developed by a third party. Since there is mapping between components and SysCap, the SysCap set of the product can be obtained after all components are assembled. -5. The SysCap set is encoded to generate the PCID. You can import the PCID to the IDE and decode it into SysCap. During development, compatibility processing is performed to mitigate the SysCap differences of devices. +5. The SysCap set is encoded to generate the PCID. You can import the PCID to DevEco Studio and decode it into SysCaps. During development, compatibility processing is performed to mitigate the SysCap differences of devices. 6. System parameters deployed on devices contain the SysCap set. The system provides native interfaces and application interfaces for components and applications to check whether a specific SysCap is available. -7. During application development, the SysCap required by the application is encoded into the Required Product Compatibility ID (RPCID) and written into the application installation package. During application installation, the package manager decodes the RPCID to obtain the SysCap required by the application and compares it with the SysCap of the device. If the SysCap required by the application is met, the application can be installed. +7. During application development, the SysCap set required by the application is encoded into the Required Product Compatibility ID (RPCID) and written into the application installation package. During application installation, the package manager decodes the RPCID to obtain the SysCap set required by the application and compares it with the SysCap set supported by the device. If the SysCap set required by the application is met, the application can be installed on the device. 8. When an application is running on a device, the **canIUse** API can be used to query whether the device is compatible with a specific SysCap. diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 74d111e369711b275ad3a548b1253d4f6c30891f..5e261f99ad0e2cae3473c8819f10a830fc944954 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -9,6 +9,7 @@ - [@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) @@ -30,6 +31,7 @@ - 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) @@ -44,7 +46,8 @@ - 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) + - Common Event and Notification - [@ohos.commonEvent](js-apis-commonEvent.md) @@ -58,6 +61,14 @@ - [@ohos.bundle](js-apis-Bundle.md) - [@ohos.bundleState](js-apis-deviceUsageStatistics.md) - [@ohos.zlib](js-apis-zlib.md) + - bundle/[AbilityInfo](js-apis-bundle-AbilityInfo.md) + - bundle/[ApplicationInfo](js-apis-bundle-ApplicationInfo.md) + - bundle/[BundleInfo](js-apis-bundle-BundleInfo.md) + - bundle/[CustomizeData](js-apis-bundle-CustomizeData.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 @@ -147,6 +158,9 @@ - [@ohos.bluetooth](js-apis-bluetooth.md) - [@ohos.connectedTag](js-apis-connectedTag.md) + - [@ohos.nfc.cardEmulation](js-apis-cardEmulation.md) + - [@ohos.nfc.controller](js-apis-nfcController.md) + - [@ohos.nfc.tag](js-apis-nfcTag.md) - [@ohos.rpc](js-apis-rpc.md) - [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifiext](js-apis-wifiext.md) @@ -180,6 +194,11 @@ - [@ohos.multimodalInput.inputDevice](js-apis-inputdevice.md) - [@ohos.multimodalInput.inputEventClient](js-apis-inputeventclient.md) - [@ohos.multimodalInput.inputMonitor](js-apis-inputmonitor.md) + - [@ohos.multimodalInput.inputEvent](js-apis-inputevent.md) + - [@ohos.multimodalInput.keyCode](js-apis-keycode.md) + - [@ohos.multimodalInput.keyEvent](js-apis-keyevent.md) + - [@ohos.multimodalInput.mouseEvent](js-apis-mouseevent.md) + - [@ohos.multimodalInput.ToucEvent](js-apis-touchevent.md) - [@ohos.power](js-apis-power.md) - [@ohos.runningLock](js-apis-runninglock.md) - [@ohos.sensor](js-apis-sensor.md) diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index 6afc672c0587ecc59c7c668a8ca773357692429d..9a037c0128fc29bd99577f44b755365396483a9b 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -143,7 +143,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { ## bundle.getAllBundleInfo -getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise> +getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise\> Obtains the information of all available bundles of a specified user in the system. This API uses a promise to return the result. @@ -166,7 +166,7 @@ SystemCapability.BundleManager.BundleFramework | Type | Description | | --------------------------- | -------------------------- | -| Promise> | Promise used to return the information of all available bundles.| +| Promise\> | Promise used to return the information of all available bundles.| **Example** @@ -185,7 +185,7 @@ bundle.getAllBundleInfo(bundleFlag, userId) ## bundle.getAllBundleInfo -getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback>): void +getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback\>): void Obtains the information of all available bundles in the system. This API uses an asynchronous callback to return the result. @@ -220,7 +220,7 @@ bundle.getAllBundleInfo(bundleFlag, (err, data) => { ## bundle.getAllBundleInfo -getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback>): void +getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback\>): void Obtains the information of all available bundles in the system. This API uses an asynchronous callback to return the result. @@ -238,7 +238,7 @@ SystemCapability.BundleManager.BundleFramework | ---------- | --------------------------------- | ---- | --------------------------------------- | | bundleFlag | BundleFlag | 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> | Yes | Callback used to return the information of all available bundles. | +| callback | AsyncCallback\> | Yes | Callback used to return the information of all available bundles. | **Example** @@ -495,7 +495,7 @@ bundle.getAllApplicationInfo(bundleFlags, (err, data) => { ## bundle.getBundleArchiveInfo -getBundleArchiveInfo(hapFilePath: string, bundleFlags: number) : Promise +getBundleArchiveInfo(hapFilePath: string, bundleFlags: number) : Promise\ Obtains information about the bundles contained in a HAP file. This API uses a promise to return the result. @@ -508,7 +508,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | | hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. The value must be greater than 0.| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. The value must be greater than or equal to 0.| **Return value** | Type | Description | @@ -530,7 +530,7 @@ bundle.getBundleArchiveInfo(hapFilePath, bundleFlags) ## bundle.getBundleArchiveInfo -getBundleArchiveInfo(hapFilePath: string, bundleFlags: number, callback: AsyncCallback) : void +getBundleArchiveInfo(hapFilePath: string, bundleFlags: number, callback: AsyncCallback\) : void Obtains information about the bundles contained in a HAP file. This API uses an asynchronous callback to return the result. @@ -543,8 +543,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | | hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. The value must be greater than 0.| -| callback| AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the information about the bundles. | +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object 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 information about the bundles.| **Example** @@ -1611,8 +1611,9 @@ Enumerates bundle flags. | GET_ABILITY_INFO_SYSTEMAPP_ONLY8+ | 0x00000080 | Obtains the ability information of system applications.| | GET_ABILITY_INFO_WITH_DISABLE8+ | 0x00000100 | Obtains information about disabled abilities. | | GET_APPLICATION_INFO_WITH_DISABLE8+ | 0x00000200 | Obtains information about disabled applications. | +| GET_APPLICATION_INFO_WITH_CERTIFICATE_FINGERPRINT 9+ | 0x00000400 | Obtains the signing certificate fingerprint of the application. | | GET_ALL_APPLICATION_INFO | 0xFFFF0000 | Obtains all application information. | -| GET_BUNDLE_WITH_HASH_VALUE9+ | 0x00000030 | Obtains the bundle information with the information about hash value. | +| GET_BUNDLE_WITH_HASH_VALUE9+ | 0x00000030 | Obtains information about the bundle that contains a hash value. | ## BundleOptions diff --git a/en/application-dev/reference/apis/js-apis-Context.md b/en/application-dev/reference/apis/js-apis-Context.md index 1a4861251195d5cfd17c4c0b2496583b29c212e7..8b2851b629aaa7ef7efaec1f2753bb655dbd1b2f 100644 --- a/en/application-dev/reference/apis/js-apis-Context.md +++ b/en/application-dev/reference/apis/js-apis-Context.md @@ -1,7 +1,9 @@ -# Context Module +# Context -> **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. +> **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 APIs of this module can be used only in the FA model. ## Modules to Import @@ -834,7 +836,7 @@ Obtains information of the current ability. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\<[AbilityInfo](#abilityInfo)> | Yes |Callback used to return the ability information.| +| callback | AsyncCallback\<[AbilityInfo](#abilityInfo)> | Yes | Callback used to return the ability information.| **Example** @@ -886,7 +888,7 @@ Obtains the context of the application. | Type | Description | | --------- |------ | -| Context |Application context.| +| Context | Application context.| **Example** @@ -928,14 +930,14 @@ Describes the HAP module information. | 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 | Modes supported by the module. | -| reqCapabilities | Array | Yes | No | Capabilities required for module running.| -| deviceTypes | Array | Yes | No | An array of supported device types.| -| abilityInfo | Array | Yes | No | Ability information. | +| 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 entrance ability. | -| installationFree | boolean | Yes | No | When installation-free is supported. | -| mainElementName | string | Yes| No| Information about the entry ability.| +| 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+ 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 1cc701b5e07e49792d320c57d2637d4caf68d717..2b1fdce8a973676f00cb4a75cd3b1d5e704d5564 100644 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ b/en/application-dev/reference/apis/js-apis-ability-context.md @@ -1,7 +1,9 @@ # AbilityContext -> **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. +> **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**. @@ -28,10 +30,10 @@ class MainAbility extends Ability { **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| abilityInfo | AbilityInfo | Yes| No| Ability information.| -| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.| +| abilityInfo | AbilityInfo | Yes| No| Ability information.| +| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.| ## AbilityContext.startAbility @@ -44,10 +46,10 @@ Starts an ability. This API uses a callback to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -55,7 +57,7 @@ Starts an ability. This API uses a callback to return the result. var want = { "deviceId": "", "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" + "abilityName": "MainAbility" }; this.context.startAbility(want, (error) => { console.log("error.code = " + error.code) @@ -73,11 +75,11 @@ Starts an ability. This API uses a callback to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| - | options | StartOptions | Yes| Parameters used for starting the ability.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| options | StartOptions | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -85,7 +87,7 @@ Starts an ability. This API uses a callback to return the result. var want = { "deviceId": "", "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" + "abilityName": "MainAbility" }; var options = { windowMode: 0, @@ -106,16 +108,16 @@ Starts an ability. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| - | options | StartOptions | No| Parameters used for starting the ability.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| options | StartOptions | No| Parameters used for starting the ability.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** @@ -123,7 +125,7 @@ Starts an ability. This API uses a promise to return the result. var want = { "deviceId": "", "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" + "abilityName": "MainAbility" }; var options = { windowMode: 0, @@ -141,16 +143,16 @@ 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 execution result when the ability is terminated. +Starts an ability. This API uses a callback to return the result when the ability is terminated. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| - | callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| **Example** @@ -169,17 +171,17 @@ Starts an ability. This API uses a callback to return the execution result when startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; -Starts an ability. This API uses a callback to return the execution result when the ability is terminated. +Starts an ability. This API uses a callback to return the result when the ability is terminated. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| - | options | StartOptions | Yes| Parameters used for starting the ability.| - | callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| options | StartOptions | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| **Example** @@ -202,23 +204,23 @@ Starts an ability. This API uses a callback to return the execution result when startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; -Starts an ability. This API uses a promise to return the execution result when the ability is terminated. +Starts an ability. This API uses a promise to return the result when the ability is terminated. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| - | options | StartOptions | No| Parameters used for starting the ability.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| options | StartOptions | No| Parameters used for starting the ability.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Promise used to return the result.| **Example** @@ -244,9 +246,9 @@ Terminates this ability. This API uses a callback to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the result indicating whether the API is successfully called.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result indicating whether the API is successfully called.| **Example** @@ -267,9 +269,9 @@ Terminates this ability. This API uses a promise to return the result. **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result indicating whether the API is successfully called.| **Example** @@ -292,10 +294,10 @@ Terminates this ability. This API uses a callback to return the information to t **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -321,15 +323,15 @@ Terminates this ability. This API uses a promise to return information to the ca **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** @@ -355,15 +357,15 @@ Obtains the caller interface of the specified ability, and if the specified abil **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, including the ability name, bundle name, and device ID. If the device ID is left blank or the default value is used, the local ability will be started.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, including the ability name, bundle name, and device ID. If the device ID is left blank or the default value is used, the local ability will be started.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<Caller> | Promise used to return the caller object to communicate with.| +| Type| Description| +| -------- | -------- | +| Promise<Caller> | Promise used to return the caller object to communicate with.| **Example** @@ -374,7 +376,7 @@ Obtains the caller interface of the specified ability, and if the specified abil onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", + abilityName: "MainAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -397,10 +399,10 @@ Requests permissions from the user by displaying a pop-up window. This API uses **Parameters** - | 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.| +| 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.| **Example** @@ -423,15 +425,15 @@ Requests permissions from the user by displaying a pop-up window. This API uses **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | permissions | Array<string> | Yes| Permissions to request.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| permissions | Array<string> | Yes| Permissions to request.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the result indicating whether the API is successfully called.| +| Type| Description| +| -------- | -------- | +| Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the result indicating whether the API is successfully called.| **Example** @@ -450,16 +452,16 @@ 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 displayed in the task. This API uses a callback to return the result. +Sets the label of the ability in the mission. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | 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.| +| 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.| **Example** @@ -474,21 +476,21 @@ Sets the label of the ability displayed in the task. This API uses a callback to setMissionLabel(label: string): Promise<void> -Sets the label of the ability displayed in the task. This API uses a promise to return the result. +Sets the label of the ability in the mission. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | label | string | Yes| Label of the ability to set.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| label | string | Yes| Label of the ability to set.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result indicating whether the API is successfully called.| **Example** @@ -499,3 +501,24 @@ Sets the label of the ability displayed in the task. This API uses a promise to console.log('failed:' + JSON.stringify(error)); }); ``` + +## AbilityContext.isTerminating + +isTerminating(): boolean; + +Checks whether this ability is in the terminating state. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| bool | The value **true** means that the ability is in terminating state, and **false** means the opposite.| + +**Example** + + ```js + var isTerminating = this.context.isTerminating(); + console.log('ability state :' + isTerminating); + ``` diff --git a/en/application-dev/reference/apis/js-apis-animator.md b/en/application-dev/reference/apis/js-apis-animator.md index d3fbcfa4e05459bfb3bad3964d5cb30eec215a56..2a9c01095ebf3ccfac93d9d96774c103fa2f6e4f 100644 --- a/en/application-dev/reference/apis/js-apis-animator.md +++ b/en/application-dev/reference/apis/js-apis-animator.md @@ -1,479 +1,240 @@ -# Animation +# Animator -> **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. -## Modules to Import -**requestAnimationFrame**: none - -**cancelAnimationFrame**: none - -**createAnimator**: +## Modules to Import ``` import animator from '@ohos.animator'; ``` -## Required Permissions - -None - -## requestAnimationFrame - -requestAnimationFrame\(handler\[, \[ ...args\]\]\): number - -Requests an animation frame. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

handler

-

Function

-

Yes

-

Handler used to request a frame. When requestAnimationFrame calls the handler, the timestamp is passed to the first parameter to indicate the time when requestAnimationFrame starts to execute the callback.

-

...args

-

Array<any>

-

No

-

Additional parameter, which is passed to the handler as a parameter during function callback.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

number

-

Request ID.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - /* xxx.css */ - .container { - flex-direction: column; - justify-content: center; - align-items: center; - width: 100%; - height: 100%; - } - .btn{ - width: 300px; - margin-top: 40px; - } - ``` - - ``` - /* xxx.js */ - export default { - data: { - requestId: 0, - startTime: 0, - }, - beginAnimation() { - cancelAnimationFrame(this.requestId); - this.requestId = requestAnimationFrame(this.runAnimation); - }, - runAnimation(timestamp) { - if (this.startTime == 0) { - this.startTime = timestamp; - } - var elapsed = timestamp - this.startTime; - if (elapsed < 500) { - console.log('callback handler timestamp: ' + timestamp); - this.requestId = requestAnimationFrame(this.runAnimation); - } - } - } - ``` - - -## cancelAnimationFrame - -cancelAnimationFrame\(requestId: number\): void - -Cancels the animation frame request. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

requestId

-

number

-

Yes

-

ID of the frame request.

-
- -- Example - - ``` - -
- - -
- ``` - - ``` - /* xxx.css */ - .container { - flex-direction: column; - justify-content: center; - align-items: center; - width: 100%; - height: 100%; - } - .btn{ - width: 300px; - margin-top: 40px; - } - ``` - - ``` - /* xxx.js */ - export default { - data: { - requestId: 0, - startTime: 0, - }, - beginAnimation() { - cancelAnimationFrame(this.requestId); - this.requestId = requestAnimationFrame(this.runAnimation); - }, - runAnimation(timestamp) { - if (this.startTime == 0) { - this.startTime = timestamp; - } - var elapsed = timestamp - this.startTime; - if (elapsed < 500) { - console.log('callback handler timestamp: ' + timestamp); - this.requestId = requestAnimationFrame(this.runAnimation); - } - }, - stopAnimation() { - cancelAnimationFrame(this.requestId); - } - } - ``` - - -## createAnimator - -createAnimator\(options\[...\]\): void - -Creates an animation object. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

options

-

Object

-

Yes

-

Attributes of the Animator to be created. For details, see the options table.

-
- -- Description of options - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

duration

-

number

-

No

-

Duration for playing an animation, in milliseconds. The default value is 0.

-

easing

-

string

-

No

-

Animation easing curve. The default value is ease.

-

delay

-

number

-

No

-

Animation delay duration, in milliseconds. The default value is 0, indicating that there is no delay.

-

fill

-

string

-

No

-

Animation start/stop mode. The default value is none. For details, see animation-fill-mode.

-

direction

-

string

-

No

-

Animation playback mode. The default value is normal. For details, see animation-direction.

-

iterations

-

number

-

No

-

Number of times that an animation is played. The default value is 1. If this parameter is set to 0, the animation is not played. If this parameter is set to -1, the animation is played for an unlimited number of times.

-

begin

-

number

-

No

-

Start point of the animation easing. If this parameter is not set, the default value 0 is used.

-

end

-

number

-

No

-

End point of the animation easing. If this parameter is not set, the default value 1 is used.

-
- -- animator interfaces - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

update

-

options

-

Updates the animation parameters. The input parameters are the same as those of createAnimator.

-

play

-

-

-

Starts an animation.

-

finish

-

-

-

Ends an animation.

-

pause

-

-

-

Pauses an animation.

-

cancel

-

-

-

Cancels an animation.

-

reverse

-

-

-

Reverses an animation.

-
- - -- **animator** supported events: - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

frame

-

number

-

The frame is requested.

-

cancel

-

-

-

The animation is forcibly canceled.

-

finish

-

-

-

The animation playback is complete.

-

repeat

-

-

-

The animation replays.

-
- -- Example - - ``` - -
-
-
+ +## createAnimator + +createAnimator(options: AnimatorOptions): AnimatorResult + +Creates an **Animator** object. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options. For details, see **AnimatorOptions**.| + +**Return value** +| Type| Description| +| -------- | -------- | +| [AnimatorResult](#animatorresult) | Animator result.| + +**Example** + + ``` + +
+
- ``` - - ``` - // js - export default { - data : { - divWidth: 200, - divHeight: 200, - animator: null - }, - onInit() { - var options = { - duration: 1500, - easing: 'friction', - fill: 'forwards', - iterations: 2, - begin: 200.0, - end: 400.0 - }; - this.animator = animator.createAnimator(options); - }, - Show() { - var options1 = { - duration: 2000, - easing: 'friction', - fill: 'forwards', - iterations: 1, - begin: 200.0, - end: 400.0 - }; - this.animator.update(options1); - var _this = this; - this.animator.onframe = function(value) { - _this.divWidth = value; - _this.divHeight = value; - }; - this.animator.play(); - } +
+ ``` + + ``` + // js + export default { + data : { + divWidth: 200, + divHeight: 200, + animator: null + }, + onInit() { + var options = { + duration: 1500, + easing: 'friction', + fill: 'forwards', + iterations: 2, + begin: 200.0, + end: 400.0 + }; + this.animator = animator.createAnimator(options); + }, + Show() { + var options1 = { + duration: 2000, + easing: 'friction', + fill: 'forwards', + iterations: 1, + begin: 200.0, + end: 400.0 + }; + this.animator.update(options1); + var _this = this; + this.animator.onframe = function(value) { + _this.divWidth = value; + _this.divHeight = value; + }; + this.animator.play(); } - ``` + } + ``` + +## AnimatorResult + +Defines the animator result. + +### update + +update(options: AnimatorOptions): void + +Updates this animator. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options.| + +**Example** +``` +animator.update(options); +``` + +### play + +play(): void + +Plays this animation. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** +``` +animator.play(); +``` + +### finish + +finish(): void + +Ends this animation. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** +``` +animator.finish(); +``` + +### pause + +pause(): void + +Pauses this animation. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** +``` +animator.pause(); +``` + +### cancel + +cancel(): void + +Cancels this animation. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** +``` +animator.cancel(); +``` + +### reverse + +reverse(): void + +Plays this animation in reverse order. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** +``` +animator.reverse(); +``` + +### onframe + +onframe: (progress: number) => void + +Called when a frame is received. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | number | Yes| Current progress of the animation.| + +**Example** +``` +animator.onframe(); +``` + +### onfinish + +onfinish: () => void + +Called when this animation is finished. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** +``` +animator.onfinish(); +``` + +### oncancel + +oncancel: () => void + +Called when this animation is canceled. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** +``` +animator.oncancel(); +``` + +### onrepeat + +onrepeat: () => void + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** +``` +animator.onrepeat(); +``` + +Called when this animation repeats. + +## AnimatorOptions + +Defines animator options. +**System capability**: SystemCapability.ArkUI.ArkUI.Full +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| duration | number | Yes| Duration for playing the animation, in milliseconds. The default value is **0**.| +| easing | string | Yes| Animation interpolation curve. The default value is **ease**.| +| delay | number | Yes| Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay.| +| fill | "none" \| "forwards" \| "backwards" \| "both" | Yes| State of the animated target after the animation is executed. The default value is **none**, which means that the target will retain its end state (defined by the last keyframe) after the animation is executed. | +| direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes| Animation playback mode. The default value is **normal**.| +| iterations | number | Yes| Number of times that the animation is played. The default value is **1**. The value **0** means not to play the animation, and **-1** means to play the animation for an unlimited number of times.| +| begin | number | Yes| Start point of the animation interpolation. If this parameter is not set, the default value **0** is used.| +| end | number | Yes| End point of the animation interpolation. If this parameter is not set, the default value **1** is used.| 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 4521fcd2b0158e67b20d36ac059cea5642a28179..c850915c4d2743d7ee8f03ce0b96d6a4f7739525 100644 --- a/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md +++ b/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md @@ -1,6 +1,5 @@ # MissionSnapshot - > **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,7 +9,7 @@ Provides the snapshot of a mission. ## Modules to Import ``` -import abilitymanager from '@ohos.application.abilityManager'; +import missionManager from '@ohos.application.missionManager' import ElementName from '@ohos.bundle'; import image from '@ohos.multimedia.image'; ``` 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 19509a5e771ce744b16a8f231faf6f75bccb772b..26c0cd030bcdf36cee488cba5066b2beba38a3d3 100644 --- a/en/application-dev/reference/apis/js-apis-application-Want.md +++ b/en/application-dev/reference/apis/js-apis-application-Want.md @@ -1,14 +1,13 @@ # Want -> **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. **Want** is the basic communication component of the system. - ## Modules to Import - ``` import Want from '@ohos.application.Want'; ``` @@ -17,14 +16,15 @@ import Want from '@ohos.application.Want'; **System capability**: SystemCapability.Ability.AbilityBase - | Name | Readable/Writable | Type | Mandatory | Description | - | ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | - | 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 directly match the specified ability. | - | abilityName | Read only | string | No | Name of the ability. If both **package** and **AbilityName** are specified in this field in a **Want** object, the **Want** object can directly match the specified ability. | - | 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. | - | entities | Read only | Array\ | No | List of entities. | +| Name | Readable/Writable| Type | Mandatory| Description | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| 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.| +| 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. | +| 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.| | 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 136ec10fb630431a12d0455ca5e941249265267e..bdf719b34ed6e7ba0dcc227ff5866c8ae7b87a87 100644 --- a/en/application-dev/reference/apis/js-apis-application-ability.md +++ b/en/application-dev/reference/apis/js-apis-application-ability.md @@ -1,15 +1,14 @@ # Ability -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. - +> **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 - ``` import Ability from '@ohos.application.Ability'; ``` @@ -23,6 +22,8 @@ import Ability from '@ohos.application.Ability'; | 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 @@ -200,11 +201,12 @@ Called to save data during the ability migration preparation process. **Example** ```js + import AbilityConstant from "@ohos.application.AbilityConstant" class myAbility extends Ability { onContinue(wantParams) { console.log('onContinue'); wantParams["myData"] = "my1234567"; - return true; + return AbilityConstant.OnContinueResult.AGREE; } } ``` @@ -212,7 +214,7 @@ Called to save data during the ability migration preparation process. ## Ability.onNewWant -onNewWant(want: Want): void; +onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; Called when the ability startup mode is set to singleton. @@ -223,13 +225,17 @@ Called when the ability startup mode is set to singleton. | 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** ```js class myAbility extends Ability { - onNewWant(want) { + onNewWant(want, launchParams) { console.log('onNewWant, want:' + want.abilityName); + if (launchParams.launchReason === AbilityConstant.LaunchReason.CONTINUATION) { + console.log('onNewWant, launchReason is continuation'); + } } } ``` @@ -259,6 +265,32 @@ Called when the configuration of the environment where the ability is running is } ``` +## Ability.dump + +dump(params: Array\): Array\; + +Called when the client information is dumped. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | params | Array\ | Yes| Parameters in the form of a command.| + +**Example** + + ```js + class myAbility extends Ability { + dump(params) { + console.log('dump, params:' + JSON.stringify(params)); + return ["params"] + } + } + ``` + + ## Caller @@ -291,6 +323,9 @@ Sends sequenceable data to the target ability. ```js import Ability from '@ohos.application.Ability'; class MyMessageAble{ // Custom sequenceable data structure + name:"" + str:"" + num: 1 constructor(name, str) { this.name = name; this.str = str; @@ -314,7 +349,7 @@ Sends sequenceable data to the target ability. onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", + abilityName: "MainAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -361,6 +396,9 @@ Sends sequenceable data to the target ability and obtains the sequenceable data ```js import Ability from '@ohos.application.Ability'; class MyMessageAble{ + name:"" + str:"" + num: 1 constructor(name, str) { this.name = name; this.str = str; @@ -384,7 +422,7 @@ Sends sequenceable data to the target ability and obtains the sequenceable data onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", + abilityName: "MainAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -423,7 +461,7 @@ Releases the caller interface of the target ability. onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", + abilityName: "MainAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -445,7 +483,7 @@ Releases the caller interface of the target ability. onRelease(callback: OnReleaseCallBack): void; -Registers a callback that is invoked when the Stub on the target ability is disconnected. +Registers a callback that is invoked when the stub on the target ability is disconnected. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore @@ -464,7 +502,7 @@ Registers a callback that is invoked when the Stub on the target ability is disc onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", + abilityName: "MainAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -509,6 +547,9 @@ Registers a caller notification callback, which is invoked when the target abili ```js import Ability from '@ohos.application.Ability'; class MyMessageAble{ + name:"" + str:"" + num: 1 constructor(name, str) { this.name = name; this.str = str; 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 8e501a482e04e33a18a8040d0183257b7c3e90c4..bb9c758f36dc8456d817cb655303591f7dfa09a7 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilitystage.md +++ b/en/application-dev/reference/apis/js-apis-application-abilitystage.md @@ -1,6 +1,6 @@ # AbilityStage -> **NOTE**
+> **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. @@ -45,15 +45,15 @@ Called when a specified ability is started. **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. | + | 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 | - | -------- | -------- | - | string | Returns an ability ID. If this ability has been started, no new instance is created and the ability is placed at the top of the stack. Otherwise, a new instance is created and started. | + | Type| Description| + | -------- | -------- | + | string | Returns an ability ID. If this ability has been started, no new instance is created and the ability is placed at the top of the stack. Otherwise, a new instance is created and started.| **Example** @@ -77,9 +77,9 @@ Called when the global configuration is updated. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-configuration.md) | Yes | Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode. | + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | config | [Configuration](js-apis-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| **Example** @@ -92,10 +92,12 @@ Called when the global configuration is updated. ``` ## AbilityStage.context +context: AbilityStageContext; + Describes the configuration information about the context. **System capability**: SystemCapability.Ability.AbilityRuntime.Core - | Name | Type | Description | - | ----------- | --------------------------- | ------------------------------------------------------------ | - | context | [AbilityStageContext](js-apis-featureAbility.md) | Called when initialization is performed during ability startup. | +| Name | Type | Description | +| ----------- | --------------------------- | ------------------------------------------------------------ | +| context | [AbilityStageContext](js-apis-featureAbility.md) | Called when initialization is performed during ability startup.| 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 0dfc9de068ba3aef8c84594b18dcad2730034cf0..517d9fb529fce872c5972a1aada50ce9f9b54ec9 100644 --- a/en/application-dev/reference/apis/js-apis-application-applicationContext.md +++ b/en/application-dev/reference/apis/js-apis-application-applicationContext.md @@ -1,11 +1,17 @@ # ApplicationContext -> **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. - +> **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 @@ -36,14 +42,6 @@ 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 - let applicationContext = this.context.getApplicationContext(); - console.log("stage applicationContext: " + JSON.stringify(applicationContext)); - let lifecycleid = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); - console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid)); - ``` ## ApplicationContext.unregisterAbilityLifecycleCallback @@ -63,9 +61,47 @@ Deregisters the listener that monitors the ability lifecycle of the application. **Example** ```js - let applicationContext = this.context.getApplicationContext(); - console.log("stage applicationContext: " + JSON.stringify(applicationContext)); - applicationContext.unregisterAbilityLifecycleCallback(lifecycleid, (error, data) => { - console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); - }); + 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)); + }); + } + } ``` 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 38ceb059efc27760cefb03b1c04fdd66a4f614e3..66cd6b7150041bdbf45d4d0e0adf105e0ade044b 100644 --- a/en/application-dev/reference/apis/js-apis-application-context.md +++ b/en/application-dev/reference/apis/js-apis-application-context.md @@ -1,8 +1,9 @@ # Context -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. - +> **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**. @@ -19,43 +20,43 @@ You must extend **AbilityContext** to implement this module. **System capability**: SystemCapability.Ability.AbilityRuntime.Core - | Name| Type| Readable| Writable| Description| + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| resourceManager | 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.| +| resourceManager | 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.| ## Context.createBundleContext createBundleContext(bundleName: string): Context; -Creates an application context. +Creates a context for a given application. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Application bundle name.| + | bundleName | string | Yes| Application bundle name.| **Return value** - | Type| Description| + | Type| Description| | -------- | -------- | - | Context | Context of the application created.| + | Context | Context created.| **Example** - + ```js import AbilityContext from '@ohos.application.Ability' class MainAbility extends AbilityContext { @@ -68,6 +69,76 @@ Creates an application context. ``` +## Context.createModuleContext + +createModuleContext(moduleName: string): Context; + +Creates a context for a given HAP. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | moduleName | string | Yes| HAP name in the application.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Context | Context created.| + +**Example** + + ```js + import AbilityContext from '@ohos.application.Ability' + class MainAbility extends AbilityContext { + onWindowStageCreate(windowStage) { + let moduleName = "module"; + let context = this.context.createModuleContext(moduleName); + } +} + + ``` + + +## Context.createModuleContext + +createModuleContext(bundleName: string, moduleName: string): Context; + +Creates a context for a given HAP in an application. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | 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.| + +**Example** + + ```js + import AbilityContext from '@ohos.application.Ability' + class MainAbility extends AbilityContext { + onWindowStageCreate(windowStage) { + let bundleName = "com.example.bundle"; + let moduleName = "module"; + let context = this.context.createModuleContext(bundleName, moduleName); + } +} + + ``` + + ## Context.getApplicationContext getApplicationContext(): ApplicationContext; @@ -83,7 +154,7 @@ Obtains the context of this application. | ApplicationContext | Current application context.| **Example** - + ```js // This part is mandatory. let applicationContext = this.context.getApplicationContext(); diff --git a/en/application-dev/reference/apis/js-apis-appmanager.md b/en/application-dev/reference/apis/js-apis-appmanager.md index 68e4bb1c64d879b3371533ab1de731ca763d4c9d..96c9bd009552016f88cc361103b15eb725828195 100644 --- a/en/application-dev/reference/apis/js-apis-appmanager.md +++ b/en/application-dev/reference/apis/js-apis-appmanager.md @@ -25,9 +25,9 @@ Checks whether this application is undergoing a stability test. This API uses an **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -49,9 +49,9 @@ Checks whether this application is undergoing a stability test. This API uses a **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -75,9 +75,9 @@ Checks whether this application is running on a RAM constrained device. This API **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -99,9 +99,9 @@ Checks whether this application is running on a RAM constrained device. This API **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -122,9 +122,9 @@ Obtains the memory size of this application. This API uses a promise to return t **Return value** - | Type| Description| - | -------- | -------- | - | Promise<number> | Size of the application memory.| +| Type| Description| +| -------- | -------- | +| Promise<number> | Size of the application memory.| **Example** @@ -146,9 +146,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<number> | No| Size of the application memory.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<number> | No| Size of the application memory.| **Example** @@ -160,7 +160,7 @@ Obtains the memory size of this application. This API uses an asynchronous callb ``` ## appManager.getProcessRunningInfos8+ -getProcessRunningInfos(): Promise>; +getProcessRunningInfos(): Promise\>; Obtains information about the running processes. This API uses a promise to return the result. @@ -168,9 +168,9 @@ Obtains information about the running processes. This API uses a promise to retu **Return value** - | Type| Description| - | -------- | -------- | - | Promise> | Promise used to return the process information.| +| Type| Description| +| -------- | -------- | +| Promise\> | Promise used to return the process information.| **Example** @@ -184,7 +184,7 @@ Obtains information about the running processes. This API uses a promise to retu ## appManager.getProcessRunningInfos8+ -getProcessRunningInfos(callback: AsyncCallback>): void; +getProcessRunningInfos(callback: AsyncCallback\>): void; Obtains information about the running processes. This API uses an asynchronous callback to return the result. @@ -192,9 +192,9 @@ Obtains information about the running processes. This API uses an asynchronous c **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback> | No| Callback used to return the process information.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback\> | No| Callback used to return the process information.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-arraylist.md b/en/application-dev/reference/apis/js-apis-arraylist.md index 2290f5d295d182f700248afc45d131bb51aea79a..a887e9a02b24275e2574ea5fac7ecee0ac49f723 100644 --- a/en/application-dev/reference/apis/js-apis-arraylist.md +++ b/en/application-dev/reference/apis/js-apis-arraylist.md @@ -1,25 +1,32 @@ # Linear Container ArrayList -> ![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. +**ArrayList** is a linear data structure that is implemented based on arrays. **ArrayList** can dynamically adjust the capacity based on project requirements. It increases the capacity by 50% each time. + +Similar to **ArrayList**, **[Vector](js-apis-vector.md)** is also implemented based on arrays and can dynamically adjust the capacity. It increases the capability by 100% each time. + +When compared with **[LinkedList](js-apis-linkedlist.md)**, **ArrayList** is more efficient in random access but less efficient in the addition or removal operation, because its addition or removal operation affects the position of other elements in the container. + +**Recommended use case**: Use **ArrayList** when elements in a container need to be frequently read. + ## Modules to Import ```ts -import ArrayList from '@ohos.util.ArrayList' +import ArrayList from '@ohos.util.ArrayList'; ``` -## System Capabilities - -SystemCapability.Utils.Lang - ## ArrayList ### Attributes +**System capability**: SystemCapability.Utils.Lang + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Number of entries in an array list (called container later).| +| length | number | Yes| No| Number of elements in an array list (called container later).| ### constructor @@ -28,6 +35,8 @@ constructor() A constructor used to create an **ArrayList** instance. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -39,19 +48,21 @@ let arrayList = new ArrayList(); add(element: T): boolean -Adds an entry at the end of this container. +Adds an element at the end of this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to add.| +| element | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the entry is added successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is added successfully; returns **false** otherwise.| **Example** @@ -69,14 +80,16 @@ Adds an entry at the end of this container. insert(element: T, index: number): void -Inserts an entry at the specified position in this container. +Inserts an element at the specified position in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to insert.| -| index | number | Yes| Index of the position where the entry is to be inserted.| +| element | T | Yes| Target element.| +| index | number | Yes| Index of the position where the element is to be inserted.| **Example** @@ -91,19 +104,21 @@ arrayList.insert(true, 2); has(element: T): boolean -Checks whether this container has the specified entry. +Checks whether this container has the specified element. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to check.| +| element | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the specified entry is contained; returns **false** otherwise.| +| boolean | Returns **true** if the specified element is contained; returns **false** otherwise.| **Example** @@ -118,19 +133,21 @@ let result1 = arrayList.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); getIndexOf(element: T): number -Obtains the index of the first occurrence of the specified entry in this container. +Obtains the index of the first occurrence of the specified element in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to query.| +| element | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| number | Returns the position index if obtained; returns **-1** if the specified entry is not found.| +| number | Returns the position index if obtained; returns **-1** if the specified element is not found.| **Example** @@ -150,19 +167,21 @@ let result = arrayList.getIndexOf(2); getLastIndexOf(element: T): number -Obtains the index of the last occurrence of the specified entry in this container. +Obtains the index of the last occurrence of the specified element in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to query.| +| element | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| number | Returns the position index if obtained; returns **-1** if the specified entry is not found.| +| number | Returns the position index if obtained; returns **-1** if the specified element is not found.| **Example** @@ -182,19 +201,21 @@ let result = arrayList.getLastIndexOf(2); removeByIndex(index: number): T -Removes an entry with the specified position from this container. +Removes an element with the specified position from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry to remove.| +| index | number | Yes| Position index of the target element.| **Return value** | Type| Description| | -------- | -------- | -| T | Entry removed.| +| T | Element removed.| **Example** @@ -212,19 +233,21 @@ let result = arrayList.removeByIndex(2); remove(element: T): boolean -Removes the first occurrence of the specified entry from this container. +Removes the first occurrence of the specified element from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to remove.| +| element | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the entry is removed successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is removed successfully; returns **false** otherwise.| **Example** @@ -241,7 +264,9 @@ let result = arrayList.remove(2); removeByRange(fromIndex: number, toIndex: number): void -Removes from this container all of the entries within a range, including the entry at the start position but not that at the end position. +Removes from this container all of the elements within a range, including the element at the start position but not that at the end position. + +**System capability**: SystemCapability.Utils.Lang **Parameters** @@ -268,7 +293,9 @@ arrayList.removeByRange(2, 6); replaceAllElements(callbackfn: (value: T, index?: number, arrlist?: ArrayList<T>) => T, thisArg?: Object): void -Replaces all entries in this container with new entries, and returns the new ones. +Replaces all elements in this container with new elements, and returns the new ones. + +**System capability**: SystemCapability.Utils.Lang **Parameters** @@ -281,8 +308,8 @@ callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Value of the entry that is currently traversed.| -| index | number | No| Position index of the entry that is currently traversed.| +| value | T | Yes| Value of the element that is currently traversed.| +| index | number | No| Position index of the element that is currently traversed.| | arrlist | ArrayList<T> | No| Instance that invokes the **replaceAllElements** method.| **Example** @@ -306,21 +333,23 @@ arrayList.replaceAllElements((value, index) => { forEach(callbackfn: (value: T, index?: number, arrlist?: ArrayList<T>) => void, thisArg?: Object): void -Uses a callback to traverse the entries in this container and obtain their position indexes. +Uses a callback to traverse the elements in this container and obtain their position indexes. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.| +| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Value of the entry that is currently traversed.| -| index | number | No| Position index of the entry that is currently traversed.| +| value | T | Yes| Value of the element that is currently traversed.| +| index | number | No| Position index of the element that is currently traversed.| | arrlist | ArrayList<T> | No| Instance that invokes the **forEach** method.| **Example** @@ -332,7 +361,7 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); arrayList.forEach((value, index) => { - console.log(value, index); + console.log("value:" + value, index); }); ``` @@ -340,7 +369,9 @@ arrayList.forEach((value, index) => { sort(comparator?: (firstValue: T, secondValue: T) => number): void -Sorts entries in this container. +Sorts elements in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** @@ -352,8 +383,8 @@ comparator | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| firstValue | T | Yes| Previous entry.| -| secondValue | T | Yes| Next entry.| +| firstValue | T | Yes| Previous element.| +| secondValue | T | Yes| Next element.| **Example** @@ -363,8 +394,8 @@ arrayList.add(2); arrayList.add(4); arrayList.add(5); arrayList.add(4); -arrayList.sort(a, (b => a - b)); -arrayList.sort(a, (b => b - a)); +arrayList.sort((a, b) => a - b); +arrayList.sort((a, b) => b - a); arrayList.sort(); ``` @@ -372,7 +403,9 @@ arrayList.sort(); subArrayList(fromIndex: number, toIndex: number): ArrayList<T> -Obtains entries within a range in this container, including the entry at the start position but not that at the end position, and returns these entries as a new **ArrayList** instance. +Obtains elements within a range in this container, including the element at the start position but not that at the end position, and returns these elements as a new **ArrayList** instance. + +**System capability**: SystemCapability.Utils.Lang **Parameters** @@ -406,6 +439,8 @@ clear(): void Clears this container and sets its length to **0**. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -423,6 +458,8 @@ clone(): ArrayList<T> Clones this container and returns a copy. The modification to the copy does not affect the original instance. +**System capability**: SystemCapability.Utils.Lang + **Return value** @@ -447,6 +484,8 @@ getCapacity(): number Obtains the capacity of this container. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -470,6 +509,8 @@ convertToArray(): Array<T> Converts this container into an array. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -491,7 +532,9 @@ let result = arrayList.convertToArray(); isEmpty(): boolean -Checks whether this container is empty (contains no entry). +Checks whether this container is empty (contains no element). + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -516,6 +559,8 @@ increaseCapacityTo(newCapacity: number): void Increases the capacity of this container. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| @@ -540,6 +585,8 @@ trimToCurrentLength(): void Trims the capacity of this container to its current length. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -557,6 +604,8 @@ arrayList.trimToCurrentLength(); Obtains an iterator, each item of which is a JavaScript object. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -574,14 +623,14 @@ arrayList.add(4); // Method 1: for (let item of arrayList) { - console.log(item); + console.log("value:" + item); } // Method 2: let iter = arrayList[Symbol.iterator](); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value:" + temp); temp = iter.next().value; } ``` diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index ba1eff24fb67f721a0c756d09382e1c0342b26d8..3a449fb0426baae2532bd3ad2f748d5af49263ec 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -1,13 +1,13 @@ # Audio Management -> **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. This module provides the following common audio-related functions: -- [AudioManager](#audiomanager): Audio management. -- [AudioRenderer](#audiorenderer8): Audio rendering, used to play Pulse Code Modulation (PCM) audio data. -- [AudioCapturer](#audiocapturer8): Audio capture, used to record PCM audio data. +- [AudioManager](#audiomanager): audio management. +- [AudioRenderer](#audiorenderer8): audio rendering, used to play Pulse Code Modulation (PCM) audio data. +- [AudioCapturer](#audiocapturer8): audio capture, used to record PCM audio data. ## Modules to Import @@ -15,22 +15,21 @@ This module provides the following common audio-related functions: import audio from '@ohos.multimedia.audio'; ``` + ## audio.getAudioManager getAudioManager(): AudioManager Obtains an **AudioManager** instance. -**System capability:** SystemCapability.Multimedia.Audio.Core - -**Return value:** - -| Type | Description | -| ----------------------------- | -------------------- | -| [AudioManager](#audiomanager) | AudioManager object. | +**System capability**: SystemCapability.Multimedia.Audio.Core -**Example:** +**Return value** +| Type | Description | +| ----------------------------- | ------------ | +| [AudioManager](#audiomanager) | **AudioManager** instance.| +**Example** ``` var audioManager = audio.getAudioManager(); ``` @@ -39,17 +38,18 @@ var audioManager = audio.getAudioManager(); createAudioRenderer(options: AudioRendererOptions, callback: AsyncCallback\): void -Obtains an **AudioRenderer** instance. This API uses an asynchronous callback to return the renderer instance. +Obtains an **AudioRenderer** instance. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** -| Name | Type | Mandatory | Description | -| :--------- | :---------------------------------------------- | :-------- | :--------------------------------------------------- | -| options | [AudioRendererOptions](#audiorendereroptions8) | Yes | Renderer configurations. | -| callback | AsyncCallback<[AudioRenderer](#audiorenderer8)> | Yes | Callback used to return the audio renderer instance. | +**Parameters** -**Example:** +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ---------------- | +| options | [AudioRendererOptions](#audiorendereroptions8) | Yes | Renderer configurations. | +| callback | AsyncCallback<[AudioRenderer](#audiorenderer8)> | Yes | Callback used to return the **AudioRenderer** instance.| + +**Example** ``` import audio from '@ohos.multimedia.audio'; @@ -81,26 +81,28 @@ audio.createAudioRenderer(audioRendererOptions,(err, data) => { } }); ``` + ## audio.createAudioRenderer8+ -createAudioRenderer(options: AudioRendererOptions): Promise +createAudioRenderer(options: AudioRendererOptions): Promise -Obtains an **AudioRenderer** instance. This API uses a promise to return the renderer instance. +Obtains an **AudioRenderer** instance. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** -| Name | Type | Mandatory | Description | -| :--------- | :--------------------------------------------- | :-------- | :---------------------------| -| options | [AudioRendererOptions](#audiorendereroptions8) | Yes | Renderer configurations. | +**Parameters** -**Return value:** +| Name | Type | Mandatory| Description | +| :------ | :--------------------------------------------- | :--- | :----------- | +| options | [AudioRendererOptions](#audiorendereroptions8) | Yes | Renderer configurations.| -| Type | Description | -| ----------------------------------------- | --------------------------------------------------- | -| Promise<[AudioRenderer](#audiorenderer8)> | Promise used to return the audio renderer instance. | +**Return value** -**Example:** +| Type | Description | +| ----------------------------------------- | ---------------- | +| Promise<[AudioRenderer](#audiorenderer8)> | Promise used to return the **AudioRenderer** instance.| + +**Example** ``` import audio from '@ohos.multimedia.audio'; @@ -136,17 +138,18 @@ audio.createAudioRenderer(audioRendererOptions).then((data) => { createAudioCapturer(options: AudioCapturerOptions, callback: AsyncCallback): void -Obtains an **AudioCapturer** instance. This API uses an asynchronous callback to return the capturer instance. +Obtains an **AudioCapturer** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**Parameters** -**Parameters:** -| Name | Type | Mandatory | Description | -| :--------- | :---------------------------------------------- | :-------- | :--------------------------------------------------- | -| options | [AudioCapturerOptions](#audiocaptureroptions8) | Yes | Capturer configurations. | -| callback | AsyncCallback<[AudioCapturer](#audiocapturer8)> | Yes | Callback used to return the audio capturer instance. | +| Name | Type | Mandatory| Description | +| :------- | :---------------------------------------------- | :--- | :--------------- | +| options | [AudioCapturerOptions](#audiocaptureroptions8) | Yes | Capturer configurations.| +| callback | AsyncCallback<[AudioCapturer](#audiocapturer8)> | Yes | Callback used to return the **AudioCapturer** instance.| -**Example:** +**Example** ``` import audio from '@ohos.multimedia.audio'; @@ -182,22 +185,23 @@ audio.createAudioCapturer(audioCapturerOptions,(err, data) => { createAudioCapturer(options: AudioCapturerOptions): Promise -Obtains an **AudioCapturer** instance. This API uses a promise to return the capturer instance. +Obtains an **AudioCapturer** instance. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Parameters:** -| Name | Type | Mandatory | Description | -| :--------- | :-------------------------------------------- | :-------- | :-------------------------- | -| options | [AudioCapturerOptions](#audiocaptureroptions8) | Yes | Capturer configurations. | +**Parameters** -**Return value:** +| Name | Type | Mandatory| Description | +| :------ | :--------------------------------------------- | :--- | :--------------- | +| options | [AudioCapturerOptions](#audiocaptureroptions8) | Yes | Capturer configurations.| -| Type | Description | -| ----------------------------------------- | --------------------------------------------------- | -| Promise<[AudioCapturer](#audiocapturer8)> | Promise used to return the audio capturer instance. | +**Return value** -**Example:** +| Type | Description | +| ----------------------------------------- | -------------- | +| Promise<[AudioCapturer](#audiocapturer8)> | Promise used to return the **AudioCapturer** instance.| + +**Example** ``` import audio from '@ohos.multimedia.audio'; @@ -230,432 +234,432 @@ audio.createAudioCapturer(audioCapturerOptions).then((data) => { ## AudioVolumeType -Enumerates audio stream types. +Enumerates the audio stream types. + +**System capability**: SystemCapability.Multimedia.Audio.Volume -**System capability:** SystemCapability.Multimedia.Audio.Volume +| Name | Default Value| Description | +| ---------------------------- | ------ | ---------- | +| VOICE_CALL8+ | 0 | Audio stream for voice calls.| +| RINGTONE | 2 | Audio stream for ringtones. | +| MEDIA | 3 | Audio stream for media purpose. | +| VOICE_ASSISTANT8+ | 9 | Audio stream for voice assistant.| -| Name | Default Value | Description | -| ---------------------------- | -------------- | --------------------------------- | -| VOICE_CALL8+ | 0 | Audio stream for voice calls. | -| RINGTONE | 2 | Audio stream for ringtones. | -| MEDIA | 3 | Audio stream for media purpose. | -| VOICE_ASSISTANT8+ | 9 | Audio stream for voice assistant. | + +## InterruptMode9+ + +Enumerates the audio interruption modes. + +**System capability**: SystemCapability.Multimedia.Audio.InterruptMode + +| Name | Default Value| Description | +| ---------------------------- | ------ | ---------- | +| SHARE_MODE | 0 | Share mode.| +| INDEPENDENT_MODE| 1 | Independent mode. | ## DeviceFlag -Enumerates audio device flags. +Enumerates the audio device flags. -**System capability:** SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value | Description | -| ------------------- | ------------- | -------------- | -| OUTPUT_DEVICES_FLAG | 1 | Output device. | -| INPUT_DEVICES_FLAG | 2 | Input device. | -| ALL_DEVICES_FLAG | 3 | All devices. | +| Name | Default Value| Description | +| ------------------- | ------ | ---------- | +| OUTPUT_DEVICES_FLAG | 1 | Output device.| +| INPUT_DEVICES_FLAG | 2 | Input device.| +| ALL_DEVICES_FLAG | 3 | All devices.| ## DeviceRole -Enumerates audio device roles. +Enumerates the audio device roles. + +**System capability**: SystemCapability.Multimedia.Audio.Device -**System capability:** SystemCapability.Multimedia.Audio.Device +| Name | Default Value| Description | +| ------------- | ------ | -------------- | +| INPUT_DEVICE | 1 | Input role.| +| OUTPUT_DEVICE | 2 | Output role.| -| Name | Default Value | Description | -| ------------- | ------------- | ------------ | -| INPUT_DEVICE | 1 | Input role. | -| OUTPUT_DEVICE | 2 | Output role. | ## DeviceType -Enumerates audio device types. +Enumerates the audio device types. -**System capability:** SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value | Description | -| ---------------- | ------------- | ------------------------------------------------------------------------ | -| INVALID | 0 | Invalid device. | -| EARPIECE | 1 | Earpiece. | -| SPEAKER | 2 | Speaker. | -| WIRED_HEADSET | 3 | Wired headset. | -| WIRED_HEADPHONES | 4 | Wired headset without microphone. | -| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links. | -| BLUETOOTH_A2DP | 8 | Bluetooth device using Advanced Audio Distribution Profile (A2DP) links. | -| MIC | 15 | Microphone. | -| USB_HEADSET | 22 | USB Type-C headset. | +| Name | Default Value| Description | +| ---------------- | ------ | --------------------------------------------------------- | +| INVALID | 0 | Invalid device. | +| EARPIECE | 1 | Earpiece. | +| SPEAKER | 2 | Speaker. | +| WIRED_HEADSET | 3 | Wired headset with a microphone. | +| WIRED_HEADPHONES | 4 | Wired headset without microphone. | +| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links. | +| BLUETOOTH_A2DP | 8 | Bluetooth device using Advanced Audio Distribution Profile (A2DP) links.| +| MIC | 15 | Microphone. | +| USB_HEADSET | 22 | USB Type-C headset. | ## ActiveDeviceType Enumerates the active device types. -**System capability:** SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value | Description | -| ------------- | ------------- | ---------------------------------------------------------------------- | -| SPEAKER | 2 | Speaker. | -| BLUETOOTH_SCO | 7 | Bluetooth device using the SCO links. | +| Name | Default Value| Description | +| ------------- | ------ | ---------------------------------------------------- | +| SPEAKER | 2 | Speaker. | +| BLUETOOTH_SCO | 7 | Bluetooth device using the SCO links.| ## AudioRingMode -Enumerates ringer modes. +Enumerates the ringer modes. -**System capability:** SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Communication -| Name | Default Value | Description | -| ------------------- | ------------- | ---------------- | -| RINGER_MODE_SILENT | 0 | Silent mode. | -| RINGER_MODE_VIBRATE | 1 | Vibration mode. | -| RINGER_MODE_NORMAL | 2 | Normal mode. | +| Name | Default Value| Description | +| ------------------- | ------ | ---------- | +| RINGER_MODE_SILENT | 0 | Silent mode.| +| RINGER_MODE_VIBRATE | 1 | Vibration mode.| +| RINGER_MODE_NORMAL | 2 | Normal mode.| ## AudioSampleFormat8+ -Enumerates the audio sample formats. +Enumerate the audio sample formats. -**System capability:** SystemCapability.Multimedia.Audio.Core +**System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value | Description | -| :-------------------- | :------------ | :------------------------------------ | -| SAMPLE_FORMAT_INVALID | -1 | Invalid format. | -| SAMPLE_FORMAT_U8 | 0 | Unsigned 8 bit integer. | -| SAMPLE_FORMAT_S16LE | 1 | Signed 16 bit integer, little endian. | -| SAMPLE_FORMAT_S24LE | 2 | Signed 24 bit integer, little endian. | -| SAMPLE_FORMAT_S32LE | 3 | Signed 32 bit integer, little endian. | +| Name | Default Value| Description | +| --------------------- | ------ | -------------------------- | +| SAMPLE_FORMAT_INVALID | -1 | Invalid format. | +| SAMPLE_FORMAT_U8 | 0 | Unsigned 8-bit integer. | +| SAMPLE_FORMAT_S16LE | 1 | Signed 16-bit integer, little endian.| +| SAMPLE_FORMAT_S24LE | 2 | Signed 24-bit integer, little endian.| +| SAMPLE_FORMAT_S32LE | 3 | Signed 32-bit integer, little endian.| ## AudioChannel8+ Enumerates the audio channels. -**System capability:** SystemCapability.Multimedia.Audio.Core +**System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value | Description | -| :-------- | :------------ | :--------------- | -| CHANNEL_1 | 0x1 << 0 | Channel count 1. | -| CHANNEL_2 | 0x1 << 1 | Channel count 2. | +| Name | Default Value | Description | +| --------- | -------- | -------- | +| CHANNEL_1 | 0x1 << 0 | Mono.| +| CHANNEL_2 | 0x1 << 1 | Dual-channel.| ## AudioSamplingRate8+ Enumerates the audio sampling rates. -**System capability:** SystemCapability.Multimedia.Audio.Core - -| Name | Default Value | Description | -| :---------------- | :------------ | :------------------- | -| SAMPLE_RATE_8000 | 8000 | Sampling rate 8000. | -| SAMPLE_RATE_11025 | 11025 | Sampling rate 11025. | -| SAMPLE_RATE_12000 | 12000 | Sampling rate 12000. | -| SAMPLE_RATE_16000 | 16000 | Sampling rate 16000. | -| SAMPLE_RATE_22050 | 22050 | Sampling rate 22050. | -| SAMPLE_RATE_24000 | 24000 | Sampling rate 24000. | -| SAMPLE_RATE_32000 | 32000 | Sampling rate 32000. | -| SAMPLE_RATE_44100 | 44100 | Sampling rate 44100. | -| SAMPLE_RATE_48000 | 48000 | Sampling rate 48000. | -| SAMPLE_RATE_64000 | 64000 | Sampling rate 64000. | -| SAMPLE_RATE_96000 | 96000 | Sampling rate 96000. | - +**System capability**: SystemCapability.Multimedia.Audio.Core + +| Name | Default Value| Description | +| ----------------- | ------ | --------------- | +| SAMPLE_RATE_8000 | 8000 | The sampling rate is 8000. | +| SAMPLE_RATE_11025 | 11025 | The sampling rate is 11025.| +| SAMPLE_RATE_12000 | 12000 | The sampling rate is 12000.| +| SAMPLE_RATE_16000 | 16000 | The sampling rate is 16000.| +| SAMPLE_RATE_22050 | 22050 | The sampling rate is 22050.| +| SAMPLE_RATE_24000 | 24000 | The sampling rate is 24000.| +| SAMPLE_RATE_32000 | 32000 | The sampling rate is 32000.| +| SAMPLE_RATE_44100 | 44100 | The sampling rate is 44100.| +| SAMPLE_RATE_48000 | 48000 | The sampling rate is 48000.| +| SAMPLE_RATE_64000 | 64000 | The sampling rate is 64000.| +| SAMPLE_RATE_96000 | 96000 | The sampling rate is 96000.| ## AudioEncodingType8+ Enumerates the audio encoding types. -**System capability:** SystemCapability.Multimedia.Audio.Core - -| Name | Default Value | Description | -| :-------------------- | :------------- | :---------------- | -| ENCODING_TYPE_INVALID | -1 | Invalid. | -| ENCODING_TYPE_RAW | 0 | PCM encoding. | +**System capability**: SystemCapability.Multimedia.Audio.Core +| Name | Default Value| Description | +| --------------------- | ------ | --------- | +| ENCODING_TYPE_INVALID | -1 | Invalid. | +| ENCODING_TYPE_RAW | 0 | PCM encoding.| ## ContentType -Enumerates the content types. - -**System capability:** SystemCapability.Multimedia.Audio.Core +Enumerates the audio content types. -| Name | Default Value | Description | -| :----------------------------------| :------------ | :---------------------- | -| CONTENT_TYPE_UNKNOWN | 0 | Unknown content. | -| CONTENT_TYPE_SPEECH | 1 | Speech content. | -| CONTENT_TYPE_MUSIC | 2 | Music content. | -| CONTENT_TYPE_MOVIE | 3 | Movie content. | -| CONTENT_TYPE_SONIFICATION | 4 | Sonification content. | -| CONTENT_TYPE_RINGTONE8+ | 5 | Ringtone content. | +**System capability**: SystemCapability.Multimedia.Audio.Core +| Name | Default Value| Description | +| ---------------------------------- | ------ | ---------- | +| CONTENT_TYPE_UNKNOWN | 0 | Unknown content.| +| CONTENT_TYPE_SPEECH | 1 | Speech. | +| CONTENT_TYPE_MUSIC | 2 | Music. | +| CONTENT_TYPE_MOVIE | 3 | Movie. | +| CONTENT_TYPE_SONIFICATION | 4 | Sonification content.| +| CONTENT_TYPE_RINGTONE8+ | 5 | Ringtone. | ## StreamUsage -Enumerates the stream usage. +Enumerates the audio stream usage. -**System capability:** SystemCapability.Multimedia.Audio.Core - -| Name | Default Value | Description | -| :--------------------------------- | :------------ | :-------------------------------- | -| STREAM_USAGE_UNKNOWN | 0 | Unknown usage. | -| STREAM_USAGE_MEDIA | 1 | Media usage. | -| STREAM_USAGE_VOICE_COMMUNICATION | 2 | Voice communication usage. | -| STREAM_USAGE_NOTIFICATION_RINGTONE | 6 | Notification or ringtone usage. | +**System capability**: SystemCapability.Multimedia.Audio.Core +| Name | Default Value| Description | +| ---------------------------------- | ------ | ---------- | +| STREAM_USAGE_UNKNOWN | 0 | Unknown usage.| +| STREAM_USAGE_MEDIA | 1 | Used for media. | +| STREAM_USAGE_VOICE_COMMUNICATION | 2 | Used for voice communication.| +| STREAM_USAGE_NOTIFICATION_RINGTONE | 6 | Used for notification.| ## AudioState8+ Enumerates the audio states. -**System capability:** SystemCapability.Multimedia.Audio.Core - -| Name | Default Value | Description | -| :------------- | :------------ | :--------------------------- | -| STATE_INVALID | -1 | Invalid state. | -| STATE_NEW | 0 | Creating new instance state. | -| STATE_PREPARED | 1 | Prepared state. | -| STATE_RUNNING | 2 | Running state. | -| STATE_STOPPED | 3 | Stopped state. | -| STATE_RELEASED | 4 | Released state. | -| STATE_PAUSED | 5 | Paused state. | +**System capability**: SystemCapability.Multimedia.Audio.Core +| Name | Default Value| Description | +| -------------- | ------ | ---------------- | +| STATE_INVALID | -1 | Invalid state. | +| STATE_NEW | 0 | Creating instance state.| +| STATE_PREPARED | 1 | Prepared. | +| STATE_RUNNING | 2 | Running. | +| STATE_STOPPED | 3 | Stopped. | +| STATE_RELEASED | 4 | Released. | +| STATE_PAUSED | 5 | Paused. | ## AudioRendererRate8+ Enumerates the audio renderer rates. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value | Description | -| :----------------- | :------------ | :------------ | -| RENDER_RATE_NORMAL | 0 | Normal rate. | -| RENDER_RATE_DOUBLE | 1 | Double rate. | -| RENDER_RATE_HALF | 2 | Half rate. | +| Name | Default Value| Description | +| ------------------ | ------ | ---------- | +| RENDER_RATE_NORMAL | 0 | Normal rate.| +| RENDER_RATE_DOUBLE | 1 | Double rate. | +| RENDER_RATE_HALF | 2 | Half rate. | ## InterruptType -Enumerates the interrupt types. - -**System capability:** SystemCapability.Multimedia.Audio.Renderer +Enumerates the audio interruption types. -| Name | Default Value | Description | -| :------------------- | :------------ | :----------------------------------- | -| INTERRUPT_TYPE_BEGIN | 1 | Audio playback interruption started. | -| INTERRUPT_TYPE_END | 2 | Audio playback interruption ended. | +**System capability**: SystemCapability.Multimedia.Audio.Renderer +| Name | Default Value| Description | +| -------------------- | ------ | ---------------------- | +| INTERRUPT_TYPE_BEGIN | 1 | Audio interruption started.| +| INTERRUPT_TYPE_END | 2 | Audio interruption ended.| ## InterruptForceType9+ -Enumerates the interrupt force types. +Enumerates the types of force that causes audio interruption. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value | Description | -| :-------------- | :------------ | :----------------------------------------- | -| INTERRUPT_FORCE | 0 | Forced action taken by system. | -| INTERRUPT_SHARE | 1 | App can choose to take action or ignore. | +| Name | Default Value| Description | +| --------------- | ------ | ------------------------------------ | +| INTERRUPT_FORCE | 0 | Forced action taken by the system. | +| INTERRUPT_SHARE | 1 | The application can choose to take action or ignore.| ## InterruptHint -Enumerates the interrupt hints. +Enumerates the hints provided along with audio interruption. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value | Description | -| :--------------------------------- | :------------ | :--------------------------- | -| INTERRUPT_HINT_NONE8+ | 0 | None. | -| INTERRUPT_HINT_RESUME | 1 | Resume the playback. | -| INTERRUPT_HINT_PAUSE | 2 | Paused/Pause the playback. | -| INTERRUPT_HINT_STOP | 3 | Stopped/Stop the playback. | -| INTERRUPT_HINT_DUCK | 4 | Ducked the playback. | -| INTERRUPT_HINT_UNDUCK8+ | 5 | Unducked the playback. | +| Name | Default Value| Description | +| ---------------------------------- | ------ | -------------------------------------------- | +| INTERRUPT_HINT_NONE8+ | 0 | None. | +| INTERRUPT_HINT_RESUME | 1 | Resume the playback. | +| INTERRUPT_HINT_PAUSE | 2 | Paused/Pause the playback. | +| INTERRUPT_HINT_STOP | 3 | Stopped/Stop the playback. | +| INTERRUPT_HINT_DUCK | 4 | Ducked the playback. (In ducking, the audio volume is reduced, but not silenced.)| +| INTERRUPT_HINT_UNDUCK8+ | 5 | Unducked the playback. | ## InterruptActionType -Enumerates the interrupt event return types. +Enumerates the returned event types for audio interruption events. -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.Multimedia.Audio.Renderer -**System capability:** SystemCapability.Multimedia.Audio.Renderer - -| Name | Default Value | Description | -| :------------- | :------------ | :---------------------------------------- | -| TYPE_ACTIVATED | 0 | Audio interrupt activated. | -| TYPE_INTERRUPT | 1 | Audio interrupted. | +| Name | Default Value| Description | +| -------------- | ------ | ------------------ | +| TYPE_ACTIVATED | 0 | Focus gain event.| +| TYPE_INTERRUPT | 1 | Audio interruption event.| ## AudioStreamInfo8+ Describes audio stream information. -**System capability:** SystemCapability.Multimedia.Audio.Core +**System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Type | Mandatory | Description | -| :------------ | :---------------------------------------- | :-------- | :-------------------- | -| samplingRate | [AudioSamplingRate](#audiosamplingrate8) | Yes | Sampling rate. | -| channels | [AudioChannel](#audiochannel8) | Yes | Audio channels. | -| sampleFormat | [AudioSampleFormat](#audiosampleformat8) | Yes | Audio sample format. | -| encodingType | [AudioEncodingType](#audioencodingtype8) | Yes | Audio encoding type. | +| Name | Type | Mandatory| Description | +| ------------ | ---------------------------------------- | ---- | ------------------ | +| samplingRate | [AudioSamplingRate](#audiosamplingrate8) | Yes | Audio sampling rate.| +| channels | [AudioChannel](#audiochannel8) | Yes | Number of audio channels.| +| sampleFormat | [AudioSampleFormat](#audiosampleformat8) | Yes | Audio sample format. | +| encodingType | [AudioEncodingType](#audioencodingtype8) | Yes | Audio encoding type. | ## AudioRendererInfo8+ Describes audio renderer information. -**System capability:** SystemCapability.Multimedia.Audio.Core +**System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Type | Mandatory | Description | -| :------------ | :-------------------------- | :-------- | :-------------------- | -| contentType | [ContentType](#contenttype) | Yes | Content type. | -| usage | [StreamUsage](#streamusage) | Yes | Stream usage. | -| rendererFlags | number | Yes | Audio renderer flags. | +| Name | Type | Mandatory| Description | +| ------------- | --------------------------- | ---- | ---------------- | +| content | [ContentType](#contenttype) | Yes | Audio content type. | +| usage | [StreamUsage](#streamusage) | Yes | Audio stream usage.| +| rendererFlags | number | Yes | Audio renderer flags.| ## AudioRendererOptions8+ -Describes audio renderer configuration options. +Describes audio renderer configurations. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Mandatory | Description | -| :------------ | :-----------------------------------------| :-------- | :-------------------- | -| streamInfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Stream information. | -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Renderer information. | +| Name | Type | Mandatory| Description | +| ------------ | ---------------------------------------- | ---- | ---------------- | +| streamInfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Audio stream information.| +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information.| -## AudioCapturerInfo8+ - -Describes audio capturer information. +## InterruptEvent9+ -**System capability:** SystemCapability.Multimedia.Audio.Core +Describes the interruption event received by the application when playback is interrupted. -| Name | Type | Mandatory | Description | -| :---------------| :------------------------- | :-------- | :-------------------- | -| source | [SourceType](#sourcetype) | Yes | Audio source type. | -| capturerFlags | number | Yes | Audio capturer flags. | +**System capability**: SystemCapability.Multimedia.Audio.Renderer -## AudioCapturerOptions8+ +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------ | ---- | ------------------------------------ | +| eventType | [InterruptType](#interrupttype) | Yes | Whether the interruption has started or ended. | +| forceType | [InterruptForceType](#interruptforcetype9) | Yes | Whether the interruption is taken by the system or to be taken by the application.| +| hintType | [InterruptHint](#interrupthint) | Yes | Hint provided along the interruption. | -Describes audio capturer configuration options. +## AudioInterrupt -**System capability:** SystemCapability.Multimedia.Audio.Capturer +Describes input parameters of audio interruption events. -| Name | Type | Mandatory | Description | -| :------------ | :-----------------------------------------| :-------- | :-------------------- | -| streamInfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Stream information. | -| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | Capturer information. | +**System capability**: SystemCapability.Multimedia.Audio.Renderer -## InterruptEvent9+ +| Name | Type | Mandatory| Description | +| --------------- | --------------------------- | ---- | ------------------------------------------------------------ | +| streamUsage | [StreamUsage](#streamusage) | Yes | Audio stream usage. | +| contentType | [ContentType](#contenttype) | Yes | Audio content type. | +| pauseWhenDucked | boolean | Yes | Whether audio playback can be paused during audio interruption. The value **true** means that audio playback can be paused during audio interruption, and **false** means the opposite.| -Describes the interrupt event received by the app when playback is interrupted. +## InterruptAction -**System capability:** SystemCapability.Multimedia.Audio.Renderer +Describes the callback invoked for audio interruption or focus gain events. -| Name | Type | Mandatory | Description | -| :-------- | :-------------------------------------------- | :-------- | :---------------------------------------------------------------- | -| eventType | [InterruptType](#interrupttype) | Yes | Whether the interruption has started or finished. | -| forceType | [InterruptForceType](#interruptforcetype9) | Yes | Whether the action is taken by system or to be taken by the app. | -| hintType | [InterruptHint](#interrupthint) | Yes | Type of action. | +**System capability**: SystemCapability.Multimedia.Audio.Renderer -## AudioInterrupt +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| actionType | [InterruptActionType](#interruptactiontype) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event.| +| type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. | +| hint | [InterruptHint](#interrupthint) | No | Hint provided along with the audio interruption event. | +| activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released.| -The parameters passed in by the audio listener event. +## VolumeEvent8+ -This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. +Describes the event received by the application when the volume is changed. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +This is a system API and cannot be called by third-party applications. -| Name | Type | Mandatory | Description | -| --------------- | --------------------------- | ---- | ------------------------------------------------------------ | -| streamUsage | [StreamUsage](#streamusage) | Yes | Audio stream usage type. | -| contentType | [ContentType](#contenttype) | Yes | Audio interrupt media type. | -| pauseWhenDucked | boolean | Yes | Whether audio playback can be paused when audio is interrupted (true means audio playback can be paused during audio interruptions and false means the opposite). | +**System capability**: SystemCapability.Multimedia.Audio.Volume -## InterruptAction +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| volume | number | Yes | Volume level. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.| +| updateUi | boolean | Yes | Whether to show the volume change in UI. | -Callback method for the audio interrupt or audio interrupt activated event. +## DeviceChangeAction -This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. +Describes the device connection status and device information. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -| actionType | [InterruptActionType](#interruptactiontype) | Yes | Event return type. TYPE_ACTIVATED is the audio interrupt activated event, and TYPE_INTERRUPT is the audio interrupt event. | -| type | [InterruptType](#interrupttype) | No | Interrupt event type. | -| hint | [InterruptHint](#interrupthint) | No | Interrupt event prompts. | -| activated | boolean | No | Acquire/release focus. true indicates that the focus acquisition/release is successful, and false indicates that the focus acquisition/release fails. | +| Name | Type | Mandatory| Description | +| :---------------- | :------------------------------------------------ | :--- | :----------------- | +| type | [DeviceChangeType](#devicechangetype) | Yes | Device connection status.| +| deviceDescriptors | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Device information. | -## VolumeEvent8+ -Describes the volume event received by the app when the volume is changed. +## DeviceChangeType -This is a system API and cannot be called by third-party applications. +Enumerates the device connection statuses. -**System capability:** SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Type | Mandatory | Description | -| :--------- | :---------------------------------- | :-------- | :--------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Volume type of the current stream. | -| volume | number | Yes | Volume level. | -| updateUi | boolean | Yes | Whether to show the volume change in UI. | +| Name | Default Value| Description | +| :--------- | :----- | :------------- | +| CONNECT | 0 | Connected. | +| DISCONNECT | 1 | Disconnected.| -## DeviceChangeAction - -Describes the device change type and device information. +## AudioCapturerOptions8+ -**System capability:** SystemCapability.Multimedia.Audio.Device +Describes audio capturer configurations. -| Name | Type | Mandatory | Description | -| :------------------ | :------------------------------------------------ | :-------- | :------------------ | -| type | [DeviceChangeType](#devicechangetype) | Yes | Device change type. | -| deviceDescriptors | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Device information. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------- | ---- | ---------------- | +| streamInfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Audio stream information.| +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo) | Yes | Audio capturer information.| -## DeviceChangeType +## AudioCapturerInfo8+ -Enumerates device change types. +Describes audio capturer information. -**System capability:** SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value | Description | -| :--------------------- | :------------ | :-------------------- | -| CONNECT | 0 | Device connection. | -| DISCONNECT | 1 | Device disconnection. | +| Name | Type | Mandatory| Description | +| :------------ | :------------------------ | :--- | :--------------- | +| source | [SourceType](#sourcetype) | Yes | Audio source type. | +| capturerFlags | number | Yes | Audio capturer flags.| ## SourceType8+ -Enumerates source types. - -**System capability:** SystemCapability.Multimedia.Audio.Core +Enumerates the audio source types. -| Name | Default Value | Description | -| :----------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------ | :------------------------------- | -| SOURCE_TYPE_INVALID | -1 | Invalid source type. | -| SOURCE_TYPE_MIC | 0 | Mic source type. | -| SOURCE_TYPE_VOICE_COMMUNICATION(This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR) | 7 | Voice communication source type. | +**System capability**: SystemCapability.Multimedia.Audio.Core +| Name | Default Value| Description | +| :------------------------------ | :----- | :--------------------- | +| SOURCE_TYPE_INVALID | -1 | Invalid audio source. | +| SOURCE_TYPE_MIC | 0 | Mic source. | +| SOURCE_TYPE_VOICE_COMMUNICATION | 7 | Voice communication source.| ## AudioScene8+ -Enumerates audio scenes. +Enumerates the audio scenes. -**System capability:** SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Communication -| Name | Default Value | Description | -| :------------------------------------------------------------------------------------ | :------------ | :---------------------- | -| AUDIO_SCENE_DEFAULT | 0 | Default audio scene. | -| AUDIO_SCENE_RINGING(system API, not supported by third-party applications) | 1 | Ringing audio scene. | -| AUDIO_SCENE_PHONE_CALL(system API, not supported by third-party applications) | 2 | Phone call audio scene. | -| AUDIO_SCENE_VOICE_CHAT | 3 | Voice chat audio scene. | +| Name | Default Value| Description | +| :--------------------- | :----- | :-------------------------------------------- | +| AUDIO_SCENE_DEFAULT | 0 | Default audio scene. | +| AUDIO_SCENE_RINGING | 1 | Ringing audio scene.
This is a system API and cannot be called by third-party applications.| +| AUDIO_SCENE_PHONE_CALL | 2 | Phone call audio scene.
This is a system API and cannot be called by third-party applications.| +| AUDIO_SCENE_VOICE_CHAT | 3 | Voice chat audio scene. | ## AudioManager -Implements audio volume and audio device management. Before calling the interface of AudioManager, you need to create an instance through [getAudioManager](#audiogetaudiomanager). +Implements audio volume and audio device management. Before calling any API in **AudioManager**, you must use [getAudioManager](#audiogetaudiomanager) to create an **AudioManager** instance. ### setVolume -setVolume\(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback\): void +setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void Sets the volume for a stream. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ---------------------------------------------------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Volume stream type. | -| volume | number | Yes | Volume to set. The value range can be obtained by calling getMinVolume and getMaxVolume. | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | -**Example:** +**Example** ``` audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { @@ -666,28 +670,29 @@ audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { console.log('Callback invoked to indicate a successful volume setting.'); }); ``` + ### setVolume -setVolume\(volumeType: AudioVolumeType, volume: number\): Promise +setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> Sets the volume for a stream. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ---------------------------------------------------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Volume stream type. | -| volume | number | Yes | Volume to set. The value range can be obtained by calling getMinVolume and getMaxVolume. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.| -**Return value:** +**Return value** -| Type | Description | -| ------------------- | ----------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| -**Example:** +**Example** ``` audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { @@ -697,20 +702,20 @@ audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { ### getVolume -getVolume\(volumeType: AudioVolumeType, callback: AsyncCallback\): void +getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -Obtains the volume of a stream. This API uses an asynchronous callback to return the query result. +Obtains the volume of a stream. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback | Yes | Callback used to return the volume. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the volume.| -**Example:** +**Example** ``` audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { @@ -722,28 +727,27 @@ audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { }); ``` - ### getVolume -getVolume\(volumeType: AudioVolumeType\): Promise +getVolume(volumeType: AudioVolumeType): Promise<number> -Obtains the volume of a stream. This API uses a promise to return the query result. +Obtains the volume of a stream. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| -**Return value:** +**Return value** -| Type | Description | -| ------------------- | ----------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| --------------------- | ------------------------- | +| Promise<number> | Promise used to return the volume.| -**Example:** +**Example** ``` audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { @@ -753,20 +757,20 @@ audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { ### getMinVolume -getMinVolume\(volumeType: AudioVolumeType, callback: AsyncCallback\): void +getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the query result. +Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback | Yes | Callback used to return the volume. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the minimum volume.| -**Example:** +**Example** ``` audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { @@ -778,28 +782,27 @@ audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { }); ``` - ### getMinVolume -getMinVolume\(volumeType: AudioVolumeType\): Promise +getMinVolume(volumeType: AudioVolumeType): Promise<number> -Obtains the minimum volume allowed for a stream. This API uses a promise to return the query result. +Obtains the minimum volume allowed for a stream. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| -**Return value:** +**Return value** -| Type | Description | -| ------------------- | ----------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| --------------------- | ------------------------- | +| Promise<number> | Promise used to return the minimum volume.| -**Example:** +**Example** ``` audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { @@ -809,20 +812,20 @@ audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { ### getMaxVolume -getMaxVolume\(volumeType: AudioVolumeType, callback: AsyncCallback\): void +getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the query result. +Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback | Yes | Callback used to return the volume. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ---------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the maximum volume.| -**Example:** +**Example** ``` audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { @@ -834,28 +837,27 @@ audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { }); ``` - ### getMaxVolume -getMaxVolume\(volumeType: AudioVolumeType\): Promise +getMaxVolume(volumeType: AudioVolumeType): Promise<number> -Obtains the maximum volume allowed for a stream. This API uses a promise to return the query result. +Obtains the maximum volume allowed for a stream. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| -**Return value:** +**Return value** -| Type | Description | -| ------------------- | ----------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| --------------------- | ----------------------------- | +| Promise<number> | Promise used to return the maximum volume.| -**Example:** +**Example** ``` audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { @@ -865,21 +867,21 @@ audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { ### mute -mute\(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback\): void +mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void -Mutes a stream. This API uses an asynchronous callback to return the result. +Mutes or unmutes a stream. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| mute | boolean | Yes | Mute status to set. The value true means to mute the stream, and false means the opposite. | -| callback | AsyncCallback | Yes | Callback used to return the volume. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | -**Example:** +**Example** ``` audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { @@ -891,29 +893,29 @@ audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { }); ``` - ### mute -mute\(volumeType: AudioVolumeType, mute: boolean\): Promise +mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> -Mutes a stream. This API uses a promise to return the result. +Mutes or unmutes a stream. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| mute | boolean | Yes | Mute status to set. The value true means to mute the stream, and false means the opposite. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite.| -**Return value:** +**Return value** -| Type | Description | -| ------------------- | ----------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** -**Example:** ``` audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { @@ -924,20 +926,20 @@ audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { ### isMute -isMute\(volumeType: AudioVolumeType, callback: AsyncCallback\): void +isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -Checks whether a stream is muted. This API uses an asynchronous callback to return the query result. +Checks whether a stream is muted. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback | Yes | Callback used to return the mute status of the stream. The value true means that the stream is muted, and false means the opposite.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ----------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite.| -**Example:** +**Example** ``` audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { @@ -952,25 +954,25 @@ audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { ### isMute -isMute\(volumeType: AudioVolumeType\): Promise +isMute(volumeType: AudioVolumeType): Promise<boolean> -Checks whether a stream is muted. This API uses a promise to return the result. +Checks whether a stream is muted. This method uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| -**Return value:** +**Return value** -| Type | Description | -| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -| Promise | Promise used to return the mute status of the stream. The value true means that the stream is muted, and false means the opposite. | +| Type | Description | +| ---------------------- | ------------------------------------------------------ | +| Promise<boolean> | Promise used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite.| -**Example:** +**Example** ``` audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { @@ -980,20 +982,20 @@ audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { ### isActive -isActive\(volumeType: AudioVolumeType, callback: AsyncCallback\) +isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -Checks whether a stream is active. This API uses an asynchronous callback to return the query result. +Checks whether a stream is active. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback | Yes | Callback used to return the active status of the stream. The value true means that the stream is active, and false means the opposite.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| -**Example:** +**Example** ``` audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { @@ -1005,28 +1007,27 @@ audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { }); ``` - ### isActive -isActive\(volumeType: AudioVolumeType\): Promise +isActive(volumeType: AudioVolumeType): Promise<boolean> -Checks whether a stream is active. This API uses a promise to return the query result. +Checks whether a stream is active. This method uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| -**Return value:** +**Return value** -| Type | Description | -| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -| Promise | Promise used to return the active status of the stream. The value true means that the stream is active, and false means the opposite. | +| Type | Description | +| ---------------------- | -------------------------------------------------------- | +| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| -**Example:** +**Example** ``` audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { @@ -1034,23 +1035,22 @@ audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { }); ``` - ### setRingerMode -setRingerMode\(mode: AudioRingMode, callback: AsyncCallback\): void +setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void Sets the ringer mode. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Communication -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ----------------------------------- | -| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | ------------------------ | +| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| -**Example:** +**Example** ``` audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { @@ -1062,28 +1062,27 @@ audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { }); ``` - ### setRingerMode -setRingerMode\(mode: AudioRingMode\): Promise +setRingerMode(mode: AudioRingMode): Promise<void> Sets the ringer mode. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Communication -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ----------------------------------- | -| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- | -------------- | +| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode.| -**Return value:** +**Return value** -| Type | Description | -| ------------------- | ----------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| -**Example:** +**Example** ``` audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { @@ -1094,19 +1093,19 @@ audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { ### getRingerMode -getRingerMode\(callback: AsyncCallback\): void +getRingerMode(callback: AsyncCallback<AudioRingMode>): void -Obtains the ringer mode. This API uses an asynchronous callback to return the query result. +Obtains the ringer mode. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Communication -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode.| -**Example:** +**Example** ``` audioManager.getRingerMode((err, value) => { @@ -1121,19 +1120,19 @@ audioManager.getRingerMode((err, value) => { ### getRingerMode -getRingerMode\(\): Promise +getRingerMode(): Promise<AudioRingMode> -Obtains the ringer mode. This API uses a promise to return the query result. +Obtains the ringer mode. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Communication -**Return value:** +**Return value** -| Type | Description | -| ---------------------------------------------- | --------------------------------------- | -| Promise<[AudioRingMode](#audioringmode)> | Promise used to return the ringer mode. | +| Type | Description | +| ---------------------------------------------- | ------------------------------- | +| Promise<[AudioRingMode](#audioringmode)> | Promise used to return the ringer mode.| -**Example:** +**Example** ``` audioManager.getRingerMode().then((value) => { @@ -1141,27 +1140,28 @@ audioManager.getRingerMode().then((value) => { }); ``` - ### setAudioParameter -setAudioParameter\(key: string, value: string, callback: AsyncCallback\): void +setAudioParameter(key: string, value: string, callback: AsyncCallback<void>): void Sets an audio parameter. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Core +This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. -**Parameters:** +**System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Type | Mandatory | Description | -| --------- | ----------------------| --------- | ------------------------------------- | -| key | string | Yes | Key of the audio parameter to set. | -| value | string | Yes | Value of the audio parameter to set. | -| callback | AsyncCallback | Yes | Callback used to return the result. | +**Parameters** -**Example:** +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------ | +| key | string | Yes | Key of the audio parameter to set. | +| value | string | Yes | Value of the audio parameter to set. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** ``` -audioManager.setAudioParameter('PBits per sample', '8 bit', (err) => { +audioManager.setAudioParameter('key_example', 'value_example', (err) => { if (err) { console.error('Failed to set the audio parameter. ${err.message}'); return; @@ -1170,56 +1170,58 @@ audioManager.setAudioParameter('PBits per sample', '8 bit', (err) => { }); ``` - ### setAudioParameter -setAudioParameter\(key: string, value: string\): Promise +setAudioParameter(key: string, value: string): Promise<void> Sets an audio parameter. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Core +This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. -**Parameters:** +**System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Type | Mandatory | Description | -| --------- | ----------------------| --------- | ------------------------------------- | -| key | string | Yes | Key of the audio parameter to set. | -| value | string | Yes | Value of the audio parameter to set. | +**Parameters** -**Return value:** +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| key | string | Yes | Key of the audio parameter to set.| +| value | string | Yes | Value of the audio parameter to set.| -| Type | Description | -| ------------------- | ----------------------------------- | -| Promise | Promise used to return the result. | +**Return value** -**Example:** +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** ``` -audioManager.setAudioParameter('PBits per sample', '8 bit').then(() => { +audioManager.setAudioParameter('key_example', 'value_example').then(() => { console.log('Promise returned to indicate a successful setting of the audio parameter.'); }); ``` - ### getAudioParameter -getAudioParameter\(key: string, callback: AsyncCallback\) +getAudioParameter(key: string, callback: AsyncCallback<string>): void -Obtains the value of an audio parameter. This API uses an asynchronous callback to return the query result. +Obtains the value of an audio parameter. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Core +This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. -**Parameters:** +**System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Type | Mandatory | Description | -| --------- | ----------------------| --------- | ---------------------------------------------------------- | -| key | string | Yes | Key of the audio parameter whose value is to be obtained. | -| callback | AsyncCallback | Yes | Callback used to return the value of the audio parameter. | +**Parameters** -**Example:** +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------- | +| key | string | Yes | Key of the audio parameter whose value is to be obtained. | +| callback | AsyncCallback<string> | Yes | Callback used to return the value of the audio parameter.| + +**Example** ``` -audioManager.getAudioParameter('PBits per sample', (err, value) => { +audioManager.getAudioParameter('key_example', (err, value) => { if (err) { console.error('Failed to obtain the value of the audio parameter. ${err.message}'); return; @@ -1228,53 +1230,52 @@ audioManager.getAudioParameter('PBits per sample', (err, value) => { }); ``` - ### getAudioParameter -getAudioParameter\(key: string\): Promise +getAudioParameter(key: string): Promise<string> -Obtains the value of an audio parameter. This API uses a promise to return the query result. +Obtains the value of an audio parameter. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Core +This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. -**Parameters:** +**System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Type | Mandatory | Description | -| --------- | ----------------------| --------- | ----------------------------------------------------------- | -| key | string | Yes | Key of the audio parameter whose value is to be obtained. | +**Parameters** -**Return value:** +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| key | string | Yes | Key of the audio parameter whose value is to be obtained.| -| Type | Description | -| ------------------- | ----------------------------------- | -| Promise | Promise used to return the value of the audio parameter. | +**Return value** -**Example:** +| Type | Description | +| --------------------- | ----------------------------------- | +| Promise<string> | Promise used to return the value of the audio parameter.| + +**Example** ``` -audioManager.getAudioParameter('PBits per sample').then((value) => { +audioManager.getAudioParameter('key_example').then((value) => { console.log('Promise returned to indicate that the value of the audio parameter is obtained.' + value); }); ``` - ### getDevices -getDevices\(deviceFlag: DeviceFlag, callback: AsyncCallback\): void +getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void -Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the query result. +Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Device -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------------------------------------- | --------- | ----------------------------------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | -| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list. | - -**Example:** +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | +| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.| +**Example** ``` audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { if (err) { @@ -1285,29 +1286,27 @@ audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { }); ``` - - ### getDevices -getDevices\(deviceFlag: DeviceFlag\): Promise +getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> -Obtains the audio devices with a specific flag. This API uses a promise to return the query result. +Obtains the audio devices with a specific flag. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Device -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| --------- | --------------------------- | --------- | ------------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ---------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| -**Return value:** +**Return value** -| Type | Description | -| ----------------------------------------------------------- | ---------------------------------------- | -| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list. | +| Type | Description | +| ------------------------------------------------------------ | ------------------------- | +| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.| -**Example:** +**Example** ``` audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { @@ -1317,21 +1316,21 @@ audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { ### setDeviceActive -setDeviceActive\(deviceType: DeviceType, active: boolean, callback: AsyncCallback\): void +setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback<void>): void Sets a device to the active state. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Device -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------------| --------- | ---------------------------------------------------------------------------------------------------------------- | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | -| active | boolean | Yes | Active status to set. The value true means to set the device to the active status, and false means the opposite. | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------------ | +| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| -**Example:** +**Example** ``` audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => { @@ -1343,31 +1342,29 @@ audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => { }); ``` - - ### setDeviceActive -setDeviceActive\(deviceType: DeviceType, active: boolean\): Promise +setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise<void> Sets a device to the active state. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Device -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------------| --------- | ---------------------------------------------------------------------------------------------------------------- | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | -| active | boolean | Yes | Active status to set. The value true means to set the device to the active status, and false means the opposite. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------ | +| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type.| +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | -**Return value:** +**Return value** -| Type | Description | -| ------------------- | ----------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| +**Example** -**Example:** ``` audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => { @@ -1375,23 +1372,22 @@ audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => { }); ``` - ### isDeviceActive -isDeviceActive\(deviceType: DeviceType, callback: AsyncCallback\): void +isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback<boolean>): void -Checks whether a device is active. This API uses an asynchronous callback to return the query result. +Checks whether a device is active. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Device -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------------| --------- | -------------------------------------------------------- | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | -| callback | AsyncCallback | Yes | Callback used to return the active status of the device. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------------ | +| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device.| -**Example:** +**Example** ``` audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { @@ -1406,25 +1402,25 @@ audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { ### isDeviceActive -isDeviceActive\(deviceType: DeviceType\): Promise +isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean> -Checks whether a device is active. This API uses a promise to return the query result. +Checks whether a device is active. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Device -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------------| --------- | ----------------------------------------- | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------ | +| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type.| -**Return value:** +**Return value** -| Type | Description | -| ------------------- | ----------------------------------- | -| Promise | Promise used to return the active status of the device. | +| Type | Description | +| ---------------------- | ------------------------------- | +| Promise<boolean> | Promise used to return the active state of the device.| -**Example:** +**Example** ``` audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => { @@ -1432,23 +1428,22 @@ audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => { }); ``` - ### setMicrophoneMute -setMicrophoneMute\(mute: boolean, callback: AsyncCallback\): void +setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Device -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| --------- | -------------------- | --------- | ---------------------------------------------------------------------------------------------- | -| mute | boolean | Yes | Mute status to set. The value true means to mute the microphone, and false means the opposite. | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | --------------------------------------------- | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | -**Example:** +**Example** ``` audioManager.setMicrophoneMute(true, (err) => { @@ -1460,30 +1455,27 @@ audioManager.setMicrophoneMute(true, (err) => { }); ``` - ### setMicrophoneMute -setMicrophoneMute\(mute: boolean\): Promise +setMicrophoneMute(mute: boolean): Promise<void> Mutes or unmutes the microphone. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Device - -**Parameters:** +**System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Type | Mandatory | Description | -| --------- | -------------------- | --------- | ---------------------------------------------------------------------------------------------- | -| mute | boolean | Yes | Mute status to set. The value true means to mute the microphone, and false means the opposite. | +**Parameters** -**Return value:** +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | --------------------------------------------- | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| -| Type | Description | -| ------------------- | ----------------------------------- | -| Promise | Promise used to return the result. | +**Return value** - +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| -**Example:** +**Example** ``` audioManager.setMicrophoneMute(true).then(() => { @@ -1491,25 +1483,23 @@ audioManager.setMicrophoneMute(true).then(() => { }); ``` - ### isMicrophoneMute -isMicrophoneMute\(callback: AsyncCallback\): void +isMicrophoneMute(callback: AsyncCallback<boolean>): void -Checks whether the microphone is muted. This API uses an asynchronous callback to return the query result. +Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Device -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| --------- | -------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the mute status of the microphone. The value true means that the microphone is muted, and false means the opposite. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| -**Example:** +**Example** ``` -var audioManager = audio.getAudioManager(); audioManager.isMicrophoneMute((err, value) => { if (err) { console.error('Failed to obtain the mute status of the microphone. ${err.message}'); @@ -1519,25 +1509,24 @@ audioManager.isMicrophoneMute((err, value) => { }); ``` - ### isMicrophoneMute -isMicrophoneMute\(\): Promise +isMicrophoneMute(): Promise<boolean> + +Checks whether the microphone is muted. This API uses a promise to return the result. -Checks whether the microphone is muted. This API uses a promise to return the query result. +**System capability**: SystemCapability.Multimedia.Audio.Device -**System capability:** SystemCapability.Multimedia.Audio.Device +**Return value** -**Return value:** +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| -| Type | Description | -| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | -| Promise | Promise used to return the mute status of the microphone. The value true means that the microphone is muted, and false means the opposite. | +**Example** -**Example:** ``` -var audioManager = audio.getAudioManager(); audioManager.isMicrophoneMute().then((value) => { console.log('Promise returned to indicate that the mute status of the microphone is obtained.', + value); }); @@ -1547,20 +1536,20 @@ audioManager.isMicrophoneMute().then((value) => { on(type: 'volumeChange', callback: Callback\): void -Subscribes to system volume change events. This API uses a callback to get volume change events. +Subscribes to system volume change events. This is a system API and cannot be called by third-party applications. -**System capability:** SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------------------------| :-------------| :------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to. The value 'volumeChange' means the system volume change event, which is triggered when a system volume change is detected. | -| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to get the system volume change event. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Type of event to subscribe to. The value **volumeChange** means the system volume change event, which is triggered when a system volume change is detected.| +| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. | -**Example:** +**Example** ``` audioManager.on('volumeChange', (volumeEvent) => { @@ -1570,25 +1559,24 @@ audioManager.on('volumeChange', (volumeEvent) => { }); ``` - ### on('ringerModeChange')8+ on(type: 'ringerModeChange', callback: Callback\): void -Subscribes to ringer mode change events. This API uses a callback to get ringer mode changes. +Subscribes to ringer mode change events. This is a system API and cannot be called by third-party applications. -**System capability:** SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Communication -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :----------------------------------------- | :-------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| type | string | Yes | Type of the event to subscribe to. The value 'ringerModeChange' means the ringer mode change event, which is triggered when a ringer mode change is detected. | -| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to get the updated ringer mode. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Type of event to subscribe to. The value **ringerModeChange** means the ringer mode change event, which is triggered when a ringer mode change is detected.| +| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the updated ringer mode. | -**Example:** +**Example** ``` audioManager.on('ringerModeChange', (ringerMode) => { @@ -1600,18 +1588,18 @@ audioManager.on('ringerModeChange', (ringerMode) => { on(type: 'deviceChange', callback: Callback): void -Subscribes to device change events. When a device is connected/disconnected, registered clients will receive the callback. +Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. -**System capability:** SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Device -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :-------------------------------------------------- | :---------| :---------------------------------------------------------------------------------------------------------------------------------------------- | -| type | string | Yes | Type of the event to subscribe to. The value 'deviceChange' means the device change event, which is triggered when a device change is detected. | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | Yes | Callback used to obtain the device update details. | +| Name | Type | Mandatory| Description | +| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | +| type | string | Yes | Type of event to subscribe to. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.| +| callback | Callback<[DeviceChangeAction](#DeviceChangeAction)\> | Yes | Callback used to return the device update details. | -**Example:** +**Example** ``` audioManager.on('deviceChange', (deviceChanged) => { @@ -1626,20 +1614,18 @@ audioManager.on('deviceChange', (deviceChanged) => { off(type: 'deviceChange', callback?: Callback): void -Unsubscribes from audio device connection change events. +Unsubscribes from device change events. -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.Multimedia.Audio.Device -**System capability:** SystemCapability.Multimedia.Audio.Device +**Parameters** -**Parameters:** +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | +| type | string | Yes | Type of event to unsubscribe from. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.| +| callback | Callback<[DeviceChangeAction](#DeviceChangeAction)> | No | Callback used to return the device update details. | -| Name | Type | Mandatory | Description | -| :------- | :-------------------------------------------------- | :---------| :-------------------------------------------------- | -| type | string | Yes | Type of the event to unsubscribe from. | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to obtain the device update details. | - -**Example:** +**Example** ``` audioManager.off('deviceChange', (deviceChanged) => { @@ -1647,26 +1633,23 @@ audioManager.off('deviceChange', (deviceChanged) => { }); ``` - ### on('interrupt') on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\): void -Subscribes to audio interrupt events. When the application's audio is interrupted by another playback event, the application will receive the callback. - -This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. +Subscribes to audio interruption events. When the application's audio is interrupted by another playback event, the application will receive the callback. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| --------- | --------------------------------------------- | ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| type | string | Yes | Type of event to subscribe to. The value 'interrupt' means the audio interrupt event, which is triggered when the audio playback of the current application is interrupted by another application.| -| interrupt | AudioInterrupt | Yes | Audio interrupt event type. | -| callback | Callback<[InterruptAction](#interruptaction)> | Yes | Audio interrupt event callback method. | +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Type of event to subscribe to. The value **interrupt** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| +| interrupt | AudioInterrupt | Yes | Audio interruption event type. | +| callback | Callback<[InterruptAction](#interruptaction)> | Yes | Callback invoked for the audio interruption event. | -**Example:** +**Example** ``` var interAudioInterrupt = { @@ -1690,21 +1673,19 @@ audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => { off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\): void -Unsubscribes from audio interrupt events. +Unsubscribes from audio interruption events. -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.Multimedia.Audio.Renderer -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**Parameters** -**Parameters:** +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Type of event to unsubscribe from. The value **interrupt** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| +| interrupt | AudioInterrupt | Yes | Audio interruption event type. | +| callback | Callback<[InterruptAction](#interruptaction)> | No | Callback invoked for the audio interruption event. | -| Name | Type | Mandatory | Description | -| --------- | --------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| type | string | Yes | Type of event to unsubscribe from. The value 'interrupt' means the audio interrupt event, which is triggered when the audio playback of the current application is interrupted by another application. | -| interrupt | AudioInterrupt | Yes | Audio interrupt event type. | -| callback | Callback<[InterruptAction](#interruptaction)> | No | Audio interrupt event callback method. | - -**Example:** +**Example** ``` var interAudioInterrupt = { @@ -1720,25 +1701,24 @@ audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => { }); ``` - ### setAudioScene8+ setAudioScene\(scene: AudioScene, callback: AsyncCallback\): void -Sets the audio scene mode to change audio strategies. This API uses an asynchronous callback to return the result. +Sets an audio scene. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. -**System capability:** SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Communication -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------------------ | :-------- | :---------------------------------- | -| scene | AudioScene | Yes | Audio scene mode. | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| :------- | :----------------------------------- | :--- | :------------------- | +| scene | AudioScene | Yes | Audio scene to set. | +| callback | AsyncCallback | Yes | Callback used to return the result.| -**Example:** +**Example** ``` audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => { @@ -1750,32 +1730,29 @@ audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => { }); ``` - ### setAudioScene8+ setAudioScene\(scene: AudioScene\): Promise -Sets the audio scene mode to change audio strategies. This API uses a promise to return the result. +Sets an audio scene. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. -**System capability:** SystemCapability.Multimedia.Audio.Communication - -**Parameters:** +**System capability**: SystemCapability.Multimedia.Audio.Communication -| Name | Type | Mandatory | Description | -| :------- | :-------------------------------------- | :-------- | :---------------- | -| scene | AudioScene | Yes | Audio scene mode. | +**Parameters** +| Name| Type | Mandatory| Description | +| :----- | :----------------------------------- | :--- | :------------- | +| scene | AudioScene | Yes | Audio scene to set.| -**Return value:** +**Return value** -| Type | Description | -| :------------- | :---------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| :------------- | :------------------- | +| Promise | Promise used to return the result.| - -**Example:** +**Example** ``` audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => { @@ -1785,22 +1762,21 @@ audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => { }); ``` - ### getAudioScene8+ getAudioScene\(callback: AsyncCallback\): void -Obtains the audio scene mode. This API uses an asynchronous callback to return the query result. +Obtains the audio scene. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Communication -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :-------------------------------------------------- | :-------- | :-------------------------------------------- | -| callback | AsyncCallback<AudioScene> | Yes | Callback used to return the audio scene mode. | +| Name | Type | Mandatory| Description | +| :------- | :-------------------------------------------------- | :--- | :--------------------------- | +| callback | AsyncCallback<AudioScene> | Yes | Callback used to return the audio scene.| -**Example:** +**Example** ``` audioManager.getAudioScene((err, value) => { @@ -1817,18 +1793,17 @@ audioManager.getAudioScene((err, value) => { getAudioScene\(\): Promise -Obtains the audio scene mode. This API uses a promise to return the query result. +Obtains the audio scene. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Communication -**Return value:** +**Return value** -| Type | Description | -| :-------------------------------------------- | :------------------------------------------- | -| Promise<AudioScene> | Promise used to return the audio scene mode. | +| Type | Description | +| :-------------------------------------------- | :--------------------------- | +| Promise<AudioScene> | Promise used to return the audio scene.| - -**Example:** +**Example** ``` audioManager.getAudioScene().then((value) => { @@ -1842,20 +1817,18 @@ audioManager.getAudioScene().then((value) => { Describes an audio device. -**System capability:** SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Type | Readable | Writable | Description | -| ---------- | ------------------------- | -------- | -------- | ------------------ | -| deviceRole | [DeviceRole](#devicerole) | Yes | No | Audio device role. | -| deviceType | [DeviceType](#devicetype) | Yes | No | Audio device type. | +| Name | Type | Readable| Writable| Description | +| ---------- | ------------------------- | ---- | ---- | ---------- | +| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role.| +| deviceType | [DeviceType](#devicetype) | Yes | No | Device type.| ## AudioDeviceDescriptors Array of [AudioDeviceDescriptor](#audiodevicedescriptor), which is read-only. -**System capability:** SystemCapability.Multimedia.Audio.Device - -**Example:** +**Example** ``` import audio from '@ohos.multimedia.audio'; @@ -1880,45 +1853,40 @@ promise.then(function (value) { } }); ``` -## AudioRenderer8+ - -Provides related APIs for audio rendering. Before calling the AudioRenderer API, you need to create an instance through [createAudioRenderer](#audiocreateaudiorenderer8). - -**System capability:** SystemCapability.Multimedia.Audio.Renderer -### state8+ +## AudioRenderer8+ -readonly state: AudioState +Provides APIs for audio rendering. Before calling any API in **AudioRenderer**, you must use [createAudioRenderer](#audiocreateaudiorenderer8) to create an **AudioRenderer** instance. -Defines the current render state. +### Attributes -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Readable | Writable | Description | -| :---- | :-------------------------- | :------- | :------- | :------------------ | -| state | [AudioState](#audiostate8) | Yes | No | Audio render state. | +| Name | Type | Readable| Writable| Description | +| ----- | -------------------------- | ---- | ---- | ------------------ | +| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state.| -**Example:** +**Example** ``` - var state = audioRenderer.state; +var state = audioRenderer.state; ``` ### getRendererInfo8+ getRendererInfo(callback: AsyncCallback): void -Obtains the renderer information provided while creating a renderer instance. This API uses an asynchronous callback to return the result. +Obtains the renderer information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------------------------------------- | :-------- | :------------------------------------------------ | -| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)> | Yes | Callback used to return the renderer information. | +| Name | Type | Mandatory| Description | +| :------- | :------------------------------------------------------- | :--- | :--------------------- | +| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information.| -**Example:** +**Example** ``` audioRenderer.getRendererInfo((err, rendererInfo) => { @@ -1929,22 +1897,21 @@ audioRenderer.getRendererInfo((err, rendererInfo) => { }); ``` - ### getRendererInfo8+ getRendererInfo(): Promise -Obtains the renderer information provided while creating a renderer instance. This API uses a promise to return the result. +Obtains the renderer information of this **AudioRenderer** instance. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value:** +**Return value** -| Type | Description | -| :-------------------------------------------------- | :----------------------------------------------- | -| Promise<[AudioRendererInfo](#audiorendererinfo8)> | Promise used to return the renderer information. | +| Type | Description | +| -------------------------------------------------- | ------------------------------- | +| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information.| -**Example:** +**Example** ``` var resultFlag = true; @@ -1957,24 +1924,23 @@ audioRenderer.getRendererInfo().then((rendererInfo) => { console.log('AudioFrameworkRenderLog: RendererInfo :ERROR: '+err.message); resultFlag = false; }); - ``` ### getStreamInfo8+ getStreamInfo(callback: AsyncCallback): void -Obtains the renderer stream information. This API uses an asynchronous callback to return the result. +Obtains the stream information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------------------------------------ | :-------- | :---------------------------------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | +| Name | Type | Mandatory| Description | +| :------- | :--------------------------------------------------- | :--- | :------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information.| -**Example:** +**Example** ``` audioRenderer.getStreamInfo((err, streamInfo) => { @@ -1990,17 +1956,17 @@ audioRenderer.getStreamInfo((err, streamInfo) => { getStreamInfo(): Promise -Obtains the renderer stream information. This API uses a promise to return the result. +Obtains the stream information of this **AudioRenderer** instance. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value:** +**Return value** -| Type | Description | -| :------------------------------------------------- | :--------------------------------------------- | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | +| Type | Description | +| :--------------------------------------------- | :--------------------- | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information.| -**Example:** +**Example** ``` audioRenderer.getStreamInfo().then((streamInfo) => { @@ -2012,7 +1978,6 @@ audioRenderer.getStreamInfo().then((streamInfo) => { }).catch((err) => { console.log('ERROR: '+err.message); }); - ``` ### start8+ @@ -2021,16 +1986,15 @@ start(callback: AsyncCallback): void Starts the renderer. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------------- | :-------- | :-------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | -| | | | | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -**Example:** +**Example** ``` audioRenderer.start((err) => { @@ -2048,15 +2012,15 @@ start(): Promise Starts the renderer. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value:** +**Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| -**Example:** +**Example** ``` audioRenderer.start().then(() => { @@ -2066,23 +2030,21 @@ audioRenderer.start().then(() => { }); ``` - ### pause8+ pause(callback: AsyncCallback\): void Pauses rendering. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------------- | :-------- | :------------------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the result. | -| | | | | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -**Example:** +**Example** ``` audioRenderer.pause((err) => { @@ -2100,15 +2062,15 @@ pause(): Promise\ Pauses rendering. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value:** +**Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| -**Example:** +**Example** ``` audioRenderer.pause().then(() => { @@ -2124,16 +2086,15 @@ drain(callback: AsyncCallback\): void Drains the playback buffer. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------------- | :-------- | :---------------------------------------| -| callback | AsyncCallback | Yes | Callback used to return the result. | -| | | | | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -**Example:** +**Example** ``` audioRenderer.drain((err) => { @@ -2151,15 +2112,15 @@ drain(): Promise\ Drains the playback buffer. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value:** +**Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| -**Example:** +**Example** ``` audioRenderer.drain().then(() => { @@ -2169,22 +2130,21 @@ audioRenderer.drain().then(() => { }); ``` - ### stop8+ stop(callback: AsyncCallback\): void Stops rendering. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------------- | :-------- | :------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -**Example:** +**Example** ``` audioRenderer.stop((err) => { @@ -2202,15 +2162,15 @@ stop(): Promise\ Stops rendering. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value:** +**Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| -**Example:** +**Example** ``` audioRenderer.stop().then(() => { @@ -2220,22 +2180,21 @@ audioRenderer.stop().then(() => { }); ``` - ### release8+ release(callback: AsyncCallback\): void Releases the renderer. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------------- | :-------- | :------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -**Example:** +**Example** ``` audioRenderer.release((err) => { @@ -2253,15 +2212,15 @@ release(): Promise\ Releases the renderer. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value:** +**Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| -**Example:** +**Example** ``` audioRenderer.release().then(() => { @@ -2277,16 +2236,16 @@ write(buffer: ArrayBuffer, callback: AsyncCallback\): void Writes the buffer. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------------- | :-------- | :--------------------------------------------------------------------------------------------------- | -| buffer | ArrayBuffer | Yes | Buffer to be written. | -| callback | AsyncCallback | Yes | Returns the number of bytes written if the operation is successful; returns an error code otherwise. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | --------------------------------------------------- | +| buffer | ArrayBuffer | Yes | Buffer to be written. | +| callback | AsyncCallback\ | Yes | Returns the number of bytes written if the operation is successful; returns an error code otherwise.| -**Example:** +**Example** ``` import audio from '@ohos.multimedia.audio'; @@ -2304,22 +2263,21 @@ audioRenderer.write(buf, (err, writtenbytes) => { }); ``` - ### write8+ write(buffer: ArrayBuffer): Promise\ Writes the buffer. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value:** +**Return value** -| Type | Description | -| :--------------- | :--------------------------------------------------------------------------------------------------- | -| Promise | Returns the number of bytes written if the operation is successful; returns an error code otherwise. | +| Type | Description | +| ---------------- | ------------------------------------------------------------ | +| Promise\ | Returns the number of bytes written if the operation is successful; returns an error code otherwise.| -**Example:** +**Example** ``` import audio from '@ohos.multimedia.audio'; @@ -2344,17 +2302,17 @@ audioRenderer.write(buf).then((writtenbytes) => { getAudioTime(callback: AsyncCallback\): void -Obtains the timestamp in Unix epoch time (starts from January 1, 1970), in nanoseconds. This API uses an asynchronous callback to return the result. +Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the timestamp. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the timestamp.| -**Example:** +**Example** ``` audioRenderer.getAudioTime((err, timestamp) => { @@ -2362,22 +2320,21 @@ audioRenderer.getAudioTime((err, timestamp) => { }); ``` - ### getAudioTime8+ getAudioTime(): Promise\ -Obtains the timestamp in Unix epoch time (starts from January 1, 1970), in nanoseconds. This API uses a promise to return the result. +Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value:** +**Return value** -| Type | Description | -| :--------------- | :------------------------------------ | -| Promise | Promise used to return the timestamp. | +| Type | Description | +| ---------------- | ----------------------- | +| Promise\ | Promise used to return the timestamp.| -**Example:** +**Example** ``` audioRenderer.getAudioTime().then((timestamp) => { @@ -2387,22 +2344,21 @@ audioRenderer.getAudioTime().then((timestamp) => { }); ``` - ### getBufferSize8+ getBufferSize(callback: AsyncCallback\): void Obtains a reasonable minimum buffer size in bytes for rendering. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :--------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the buffer size. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the buffer size.| -**Example:** +**Example** ``` var bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { @@ -2412,22 +2368,21 @@ var bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { }); ``` - ### getBufferSize8+ getBufferSize(): Promise\ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value:** +**Return value** -| Type | Description | -| :--------------- | :-------------------------------------- | -| Promise | Promise used to return the buffer size. | +| Type | Description | +| ---------------- | --------------------------- | +| Promise\ | Promise used to return the buffer size.| -**Example:** +**Example** ``` var bufferSize; @@ -2445,16 +2400,16 @@ setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void Sets the render rate. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------------------------ | :-------- | :---------------------------------- | -| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -**Example:** +**Example** ``` audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => { @@ -2466,28 +2421,27 @@ audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => }); ``` - ### setRenderRate8+ setRenderRate(rate: AudioRendererRate): Promise\ Sets the render rate. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :--- | :--------------------------------------- | :-------- | :----------------- | -| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------------- | ---- | ------------ | +| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate.| -**Return value:** +**Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| -**Example:** +**Example** ``` audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => { @@ -2503,15 +2457,15 @@ getRenderRate(callback: AsyncCallback\): void Obtains the current render rate. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------------------------------------- | :-------- | :--------------------------------------------- | -| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)\> | Yes | Callback used to return the audio render rate. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------ | +| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate.| -**Example:** +**Example** ``` audioRenderer.getRenderRate((err, renderrate) => { @@ -2519,22 +2473,21 @@ audioRenderer.getRenderRate((err, renderrate) => { }); ``` - ### getRenderRate8+ getRenderRate(): Promise\ Obtains the current render rate. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value:** +**Return value** -| Type | Description | -| :-------------------------------------------------- | :-------------------------------------------- | -| Promise<<[AudioRendererRate](#audiorendererrate8)\> | Promise used to return the audio render rate. | +| Type | Description | +| ------------------------------------------------- | ------------------------- | +| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate.| -**Example:** +**Example** ``` audioRenderer.getRenderRate().then((renderRate) => { @@ -2543,24 +2496,71 @@ audioRenderer.getRenderRate().then((renderRate) => { console.log('ERROR: '+err.message); }); ``` +### setInterruptMode9+ + +setInterruptMode(interruptMode: InterruptMode): Promise<void> + +Sets the audio interruption mode for the application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| interruptMode | [InterruptMode](#InterruptMode) | Yes | Audio interruption mode. | + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned.| + +**Example** + +``` +audioManager.setInterruptMode(audio.InterruptType.SHARE_MODE).then(() => { + console.log('Promise returned to indicate a successful volume setting.'); +}); +``` +### setInterruptMode9+ + +setInterruptMode(interruptMode: InterruptMode, callback: Callback\): void + +Sets the audio interruption mode for the application. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** +| Name| Type| Mandatory| Description | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +|interruptMode | [InterruptMode](#InterruptMode) | Yes | Audio interruption mode.| +|callback | Callback\ | Yes |Callback used to return the result.| +**Example** + +``` +audioManager.setInterruptMode(audio.InterruptType.SHARE_MODE,()=>{ + console.log('Callback returned to indicate a successful volume setting.'); +}); +``` ### on('interrupt')9+ on(type: 'interrupt', callback: Callback\): void -Subscribes to audio interrupt events. This API uses a callback to get interrupt events. The interrupt event is triggered when audio rendering is interrupted. +Subscribes to audio interruption events. This API uses a callback to get interrupt events. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :-------------------------------------------- | :-------- | :---------------------------------------------- | -| type | string | Yes | Type of the playback event to subscribe to. | -| callback | Callback<[InterruptEvent](#interruptevent9)\> | Yes | Callback used to listen for interrupt callback. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Type of event to subscribe to. The value **interrupt** means the audio interruption event, which is triggered when audio playback is interrupted.| +| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | -**Example:** +**Example** ``` var isPlay; @@ -2583,10 +2583,10 @@ audioRenderer.on('interrupt', async(interruptEvent) => { console.log('Resume force paused renderer or ignore'); await audioRenderer.start().then(async function () { console.info('AudioInterruptMusic: renderInstant started :SUCCESS '); - started = true; + started = true; }).catch((err) => { - console.info('AudioInterruptMusic: renderInstant start :ERROR : '+err.message); - started = false; + console.info('AudioInterruptMusic: renderInstant start :ERROR : '+err.message); + started = false; }); if (started) { isPlay = true; @@ -2615,19 +2615,19 @@ audioRenderer.on('interrupt', async(interruptEvent) => { on(type: 'markReach', frame: number, callback: (position: number) => {}): void -Subscribes to mark reached events. When the number of frames rendered reaches the value of the frame parameter, the callback is invoked. +Subscribes to mark reached events. When the number of frames rendered reaches the value of the **frame** parameter, the callback is invoked. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------ | :-------- | :----------------------------------------------------------------------- | -| type | string | Yes | Type of the renderer event to subscribe to. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than 0. | -| callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory| Description | +| :------- | :----------------------- | :--- | :---------------------------------------- | +| type | string | Yes | Type of event to subscribe to. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | -**Example:** +**Example** ``` audioRenderer.on('markReach', 1000, (position) => { @@ -2644,15 +2644,15 @@ off(type: 'markReach'): void Unsubscribes from mark reached events. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------ | :-------- | :----------------------------------------------- | -| type | string | Yes | Type of the renderer event to unsubscribe from. | +| Name| Type | Mandatory| Description | +| :----- | :----- | :--- | :------------------------------------------------ | +| type | string | Yes | Type of event to unsubscribe from. The value is fixed at **markReach**.| -**Example:** +**Example** ``` audioRenderer.off('markReach'); @@ -2662,19 +2662,19 @@ audioRenderer.off('markReach'); on(type: "periodReach", frame: number, callback: (position: number) => {}): void -Subscribes to period reached events. When the period of frame rendering reaches the value of frame parameter, the callback is invoked. +Subscribes to period reached events. When the period of frame rendering reaches the value of the **frame** parameter, the callback is invoked. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------ | :-------- | :--------------------------------------------------------------------------------- | -| type | string | Yes | Type of the renderer event to subscribe to. | -| frame | number | Yes | Period during which frame rendering is listened. The value must be greater than 0. | -| callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory| Description | +| :------- | :----------------------- | :--- | :------------------------------------------ | +| type | string | Yes | Type of event to subscribe to. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter.| +| frame | number | Yes | Period during which frame rendering is listened. The value must be greater than **0**. | +| callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | -**Example:** +**Example** ``` audioRenderer.on('periodReach', 1000, (position) => { @@ -2690,15 +2690,15 @@ off(type: 'periodReach'): void Unsubscribes from period reached events. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------ | :-------- | :----------------------------------------------- | -| type | string | Yes | Type of the renderer event to unsubscribe from. | +| Name| Type | Mandatory| Description | +| :----- | :----- | :--- | :-------------------------------------------------- | +| type | string | Yes | Type of event to unsubscribe from. The value is fixed at **periodReach**.| -**Example:** +**Example** ``` audioRenderer.off('periodReach') @@ -2710,16 +2710,16 @@ on(type: 'stateChange', callback: Callback): void Subscribes to state change events. -**System capability:** SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------- | :-------- | :--------------------------------------------------------------------------------------- | -| type | string | Yes | Type of the event to subscribe to. The value 'stateChange' means the state change event. | -| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | +| Name | Type | Mandatory| Description | +| :------- | :------------------------- | :--- | :------------------------------------------ | +| type | string | Yes | Type of event to subscribe to. The value **stateChange** means the state change event.| +| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | -**Example:** +**Example** ``` audioRenderer.on('stateChange', (state) => { @@ -2734,42 +2734,37 @@ audioRenderer.on('stateChange', (state) => { ## AudioCapturer8+ -Provides related APIs for audio capture. Before calling the API of AudioCapturer, you need to create an instance through [createAudioCapturer](#audiocreateaudiocapturer8). - -### state8+ +Provides APIs for audio capture. Before calling any API in **AudioCapturer**, you must use [createAudioCapturer](#audiocreateaudiocapturer8) to create an **AudioCapturer** instance. -readonly state: AudioState +### Attributes -Defines the current capture state. +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**System capability:** SystemCapability.Multimedia.Audio.Capturer +| Name | Type | Readable| Writable| Description | +| :---- | :------------------------- | :--- | :--- | :--------------- | +| state8+ | [AudioState](#audiostate8) | Yes| No | Audio capturer state.| -| Name | Type | Readable | Writable | Description | -| :---- | :------------------------- | :------- | :------- | :------------------- | -| state | [AudioState](#audiostate8) | Yes | No | Audio capture state. | - -**Example:** +**Example** ``` var state = audioCapturer.state; ``` - ### getCapturerInfo8+ getCapturerInfo(callback: AsyncCallback): void -Obtains the capturer information provided while creating a capturer instance. This API uses an asynchronous callback to return the result. +Obtains the capturer information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------------------------------------- | :-------- | :------------------------------------------------ | -| callback | AsyncCallback<[AudioCapturerInfo](#audiocapturerinfo)\> | Yes | Callback used to return the capturer information. | +| Name | Type | Mandatory| Description | +| :------- | :-------------------------------- | :--- | :----------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the capturer information.| -**Example:** +**Example** ``` audioCapturer.getCapturerInfo((err, capturerInfo) => { @@ -2788,17 +2783,17 @@ audioCapturer.getCapturerInfo((err, capturerInfo) => { getCapturerInfo(): Promise -Obtains the capturer information provided while creating a capturer instance. This API uses a promise to return the result. +Obtains the capturer information of this **AudioCapturer** instance. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Return value:** +**Return value** -| Type | Description | -| :-------------------------------------------------- | :----------------------------------------------- | -| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information. | +| Type | Description | +| :------------------------------------------------ | :---------------------------------- | +| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information.| -**Example:** +**Example** ``` audioCapturer.getCapturerInfo().then((audioParamsGet) => { @@ -2813,24 +2808,23 @@ audioCapturer.getCapturerInfo().then((audioParamsGet) => { }).catch((err) => { console.log('AudioFrameworkRecLog: CapturerInfo :ERROR: '+err.message); }); - ``` ### getStreamInfo8+ getStreamInfo(callback: AsyncCallback): void -Obtains the capturer stream information. This API uses an asynchronous callback to return the result. +Obtains the stream information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :----------------------------------------------------------- | :-------- | :---------------------------------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | +| Name | Type | Mandatory| Description | +| :------- | :--------------------------------------------------- | :--- | :------------------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information.| -**Example:** +**Example** ``` audioCapturer.getStreamInfo((err, streamInfo) => { @@ -2850,17 +2844,17 @@ audioCapturer.getStreamInfo((err, streamInfo) => { getStreamInfo(): Promise -Obtains the capturer stream information. This API uses a promise to return the result. +Obtains the stream information of this **AudioCapturer** instance. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Return value:** +**Return value** -| Type | Description | -| :---------------------------------------------------- | :----------------------------------------------- | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | +| Type | Description | +| :--------------------------------------------- | :------------------------------ | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information.| -**Example:** +**Example** ``` audioCapturer.getStreamInfo().then((audioParamsGet) => { @@ -2872,7 +2866,6 @@ audioCapturer.getStreamInfo().then((audioParamsGet) => { }).catch((err) => { console.log('getStreamInfo :ERROR: ' + err.message); }); - ``` ### start8+ @@ -2881,15 +2874,15 @@ start(callback: AsyncCallback): void Starts capturing. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------------- | :-------- | :-------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| :------- | :------------------- | :--- | :----------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| -**Example:** +**Example** ``` audioCapturer.start((err) => { @@ -2908,15 +2901,15 @@ start(): Promise Starts capturing. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Return value:** +**Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| :------------- | :---------------------------- | +| Promise | Promise used to return the result.| -**Example:** +**Example** ``` audioCapturer.start().then(() => { @@ -2939,15 +2932,15 @@ stop(callback: AsyncCallback): void Stops capturing. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------------- | :-------- | :------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| :------- | :------------------- | :--- | :----------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| -**Example:** +**Example** ``` audioCapturer.stop((err) => { @@ -2966,15 +2959,15 @@ stop(): Promise Stops capturing. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Return value:** +**Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| :------------- | :---------------------------- | +| Promise | Promise used to return the result.| -**Example:** +**Example** ``` audioCapturer.stop().then(() => { @@ -2990,22 +2983,21 @@ audioCapturer.stop().then(() => { }); ``` - ### release8+ release(callback: AsyncCallback): void -Releases the capturer. This API uses an asynchronous callback to return the result. +Releases this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------------- | :-------- | :------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| :------- | :------------------- | :--- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | -**Example:** +**Example** ``` audioCapturer.release((err) => { @@ -3022,20 +3014,19 @@ audioCapturer.release((err) => { release(): Promise -Releases the capturer. This API uses a promise to return the result. +Releases this **AudioCapturer** instance. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Return value:** +**Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| :------------- | :---------------------------- | +| Promise | Promise used to return the result.| -**Example:** +**Example** ``` - audioCapturer.release().then(() => { console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); @@ -3046,7 +3037,6 @@ audioCapturer.release().then(() => { console.info('AudioFrameworkRecLog: Capturer stop:ERROR : '+err.message); stateFlag=false }); - ``` @@ -3054,19 +3044,19 @@ audioCapturer.release().then(() => { read(size: number, isBlockingRead: boolean, callback: AsyncCallback): void -Reads the buffer from the audio capturer. This API uses an asynchronous callback to return the result. +Reads the buffer. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------------- | :-------------------------- | :-------- | :-------------------------------------------- | -| size | number | Yes | Number of bytes to read. | -| isBlockingRead | boolean | Yes | Whether the read operation should be blocked. | -| callback | AsyncCallback | Yes | Callback used to return the buffer. | +| Name | Type | Mandatory| Description | +| :------------- | :-------------------------- | :--- | :------------------------------- | +| size | number | Yes | Number of bytes to read. | +| isBlockingRead | boolean | Yes | Whether to block the read operation. | +| callback | AsyncCallback | Yes | Callback used to return the buffer.| -**Example:** +**Example** ``` audioCapturer.read(bufferSize, true, async(err, buffer) => { @@ -3081,24 +3071,24 @@ audioCapturer.read(bufferSize, true, async(err, buffer) => { read(size: number, isBlockingRead: boolean): Promise -Reads the buffer from the audio capturer. This API uses a promise to return the result. +Reads the buffer. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------------- | :--------- | :-------- | :-------------------------------------------- | -| size | number | Yes | Number of bytes to read. | -| isBlockingRead | boolean | Yes | Whether the read operation should be blocked. | +| Name | Type | Mandatory| Description | +| :------------- | :------ | :--- | :--------------- | +| size | number | Yes | Number of bytes to read. | +| isBlockingRead | boolean | Yes | Whether to block the read operation.| -**Return value:** +**Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------------------------------------------- | -| Promise | Returns the buffer data read if the operation is successful; returns an error code otherwise. | +| Type | Description | +| :-------------------- | :----------------------------------------------------- | +| Promise | Returns the buffer data read if the operation is successful; returns an error code otherwise.| -**Example:** +**Example** ``` audioCapturer.read(bufferSize, true).then((buffer) => { @@ -3113,18 +3103,17 @@ audioCapturer.read(bufferSize, true).then((buffer) => { getAudioTime(callback: AsyncCallback): void -Obtains the timestamp in Unix epoch time (starts from January 1, 1970), in nanoseconds. This API uses an asynchronous callback to return the result. +Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the timestamp. | -| | | | | +| Name | Type | Mandatory| Description | +| :------- | :--------------------- | :--- | :----------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the timestamp.| -**Example:** +**Example** ``` audioCapturer.getAudioTime((err, timestamp) => { @@ -3137,17 +3126,17 @@ audioCapturer.getAudioTime((err, timestamp) => { getAudioTime(): Promise -Obtains the timestamp in Unix epoch time (starts from January 1, 1970), in nanoseconds. This API uses a promise to return the result. +Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Return value:** +**Return value** -| Type | Description | -| :--------------- | :------------------------------------ | -| Promise | Promise used to return the timestamp. | +| Type | Description | +| :--------------- | :---------------------------- | +| Promise | Promise used to return the timestamp.| -**Example:** +**Example** ``` audioCapturer.getAudioTime().then((audioTime) => { @@ -3155,7 +3144,6 @@ audioCapturer.getAudioTime().then((audioTime) => { }).catch((err) => { console.info('AudioFrameworkRecLog: AudioCapturer Created : ERROR : '+err.message); }); - ``` @@ -3165,16 +3153,15 @@ getBufferSize(callback: AsyncCallback): void Obtains a reasonable minimum buffer size in bytes for capturing. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :--------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the buffer size. | -| | | | | +| Name | Type | Mandatory| Description | +| :------- | :--------------------- | :--- | :----------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the buffer size.| -**Example:** +**Example** ``` audioCapturer.getBufferSize((err, bufferSize) => { @@ -3189,21 +3176,22 @@ audioCapturer.getBufferSize((err, bufferSize) => { }); ``` + ### getBufferSize8+ getBufferSize(): Promise Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a promise to return the result. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Return value:** +**Return value** -| Type | Description | -| :--------------- | :-------------------------------------- | -| Promise | Promise used to return the buffer size. | +| Type | Description | +| :--------------- | :---------------------------------- | +| Promise | Promise used to return the buffer size.| -**Example:** +**Example** ``` await audioCapturer.getBufferSize().then(async function (bufferSize) { @@ -3215,23 +3203,24 @@ await audioCapturer.getBufferSize().then(async function (bufferSize) { }); ``` + ### on('markReach')8+ on(type: 'markReach', frame: number, callback: (position: number) => {}): void -Subscribes to mark reached events. When the number of frames captured reaches the value of the frame parameter, the callback is invoked. +Subscribes to mark reached events. When the number of frames captured reaches the value of the **frame** parameter, the callback is invoked. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------ | :-------- | :----------------------------------------------------------------------- | -| type | string | Yes | Type of the capturer event to subscribe to. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than 0. | -| callback | position: number) => {} | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory| Description | +| :------- | :---------------------- | :--- | :----------------------------------------- | +| type | string | Yes | Type of event to subscribe to. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | position: number) => {} | Yes | Callback invoked when the event is triggered.| -**Example:** +**Example** ``` audioCapturer.on('markReach', 1000, (position) => { @@ -3241,22 +3230,21 @@ audioCapturer.on('markReach', 1000, (position) => { }); ``` - ### off('markReach')8+ off(type: 'markReach'): void -Unsubscribes from the mark reached events. +Unsubscribes from mark reached events. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------ | :-------- | :---------------------------------------------- | -| type | string | Yes | Type of the capturer event to unsubscribe from. | +| Name| Type | Mandatory| Description | +| :----- | :----- | :--- | :-------------------------------------------- | +| type | string | Yes | Type of event to unsubscribe from. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| -**Example:** +**Example** ``` audioCapturer.off('markReach'); @@ -3266,19 +3254,19 @@ audioCapturer.off('markReach'); on(type: "periodReach", frame: number, callback: (position: number) => {}): void -Subscribes to period reached events. When the period of frame capturing reaches the value of frame parameter, the callback is invoked. +Subscribes to mark reached events. When the period of frame capturing reaches the value of the **frame** parameter, the callback is invoked. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------ | :-------- | :--------------------------------------------------------------------------------- | -| type | string | Yes | Type of the capturer event to subscribe to. | -| frame | number | Yes | Period during which frame capturing is listened. The value must be greater than 0. | -| callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory| Description | +| :------- | :----------------------- | :--- | :------------------------------------------ | +| type | string | Yes | Type of event to subscribe to. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter.| +| frame | number | Yes | Period during which frame capturing is listened. The value must be greater than **0**. | +| callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | -**Example:** +**Example** ``` audioCapturer.on('periodReach', 1000, (position) => { @@ -3294,15 +3282,15 @@ off(type: 'periodReach'): void Unsubscribes from period reached events. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------ | :-------- | :---------------------------------------------- | -| type | string | Yes | Type of the capturer event to unsubscribe from. | +| Name| Type | Mandatory| Description | +| :----- | :----- | :--- | :---------------------------------------------- | +| type | string | Yes | Type of event to unsubscribe from. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter.| -**Example:** +**Example** ``` audioCapturer.off('periodReach') @@ -3314,16 +3302,16 @@ on(type: 'stateChange', callback: Callback): void Subscribes to state change events. -**System capability:** SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Parameters:** +**Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------- | :-------- | :--------------------------------------------------------------------------------------- | -| type | string | Yes | Type of the event to subscribe to. The value 'stateChange' means the state change event. | -| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | +| Name | Type | Mandatory| Description | +| :------- | :------------------------- | :--- | :------------------------------------------ | +| type | string | Yes | Type of event to subscribe to. The value **stateChange** means the state change event.| +| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | -**Example:** +**Example** ``` audioCapturer.on('stateChange', (state) => { diff --git a/en/application-dev/reference/apis/js-apis-battery-info.md b/en/application-dev/reference/apis/js-apis-battery-info.md index 499c9eb52e7853f781915ff7eed3f2c5e8cbfaee..135400833c36005e1504b32f56f353cd2f271e40 100644 --- a/en/application-dev/reference/apis/js-apis-battery-info.md +++ b/en/application-dev/reference/apis/js-apis-battery-info.md @@ -1,12 +1,12 @@ -# Battery Info +# Battery Info ->![](../../public_sys-resources/icon-note.gif) **NOTE** +>![](../../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 Battery Info module provides APIs for querying the charger type, battery health status, and battery charging status. -## Modules to Import +## Modules to Import ```js import batteryInfo from '@ohos.batteryInfo'; @@ -16,264 +16,63 @@ import batteryInfo from '@ohos.batteryInfo'; SystemCapability.PowerManager.BatteryManager -## Attributes +## Attributes Describes battery information. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Readable

-

Writable

-

Description

-

batterySOC

-

number

-

Yes

-

No

-

Battery state of charge (SoC) of the current device, in unit of percentage.

-

chargingStatus

-

BatteryChargeState

-

Yes

-

No

-

Battery charging state of the current device.

-

healthStatus

-

BatteryHealthState

-

Yes

-

No

-

Battery health state of the current device.

-

pluggedType

-

BatteryPluggedType

-

Yes

-

No

-

Charger type of the current device.

-

voltage

-

number

-

Yes

-

No

-

Battery voltage of the current device, in unit of microvolt.

-

technology

-

string

-

Yes

-

No

-

Battery technology of the current device.

-

batteryTemperature

-

number

-

Yes

-

No

-

Battery temperature of the current device, in unit of 0.1°C.

-

isBatteryPresent7+

-

boolean

-

Yes

-

No

-

Whether the battery is supported or present.

-
+| Name | Type | Readable | Writable | Description | +| ----------------------------- | ----------------------------------------- | -------- | -------- | ------------------------------------------------------------ | +| batterySOC | number | Yes | No | Battery state of charge (SoC) of the current device, in unit of percentage. | +| chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the current device. | +| healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health state of the current device. | +| pluggedType | [BatteryPluggedType](#batterypluggertype) | Yes | No | Charger type of the current device. | +| voltage | number | Yes | No | Battery voltage of the current device, in unit of microvolt. | +| technology | string | Yes | No | Battery technology of the current device. | +| batteryTemperature | number | Yes | No | Battery temperature of the current device, in unit of 0.1°C. | +| isBatteryPresent7+ | boolean | Yes | No | Whether the battery is supported or present. | -- Example +**Example** - ```js - import batteryInfo from '@ohos.batteryInfo'; - var batterySoc = batteryInfo.batterySOC; - ``` +```js +import batteryInfo from '@ohos.batteryInfo'; +var batterySoc = batteryInfo.batterySOC; +``` -## BatteryPluggedType +## BatteryPluggedType Enumerates charger types. - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

NONE

-

0

-

Unknown type

-

AC

-

1

-

AC charger

-

USB

-

2

-

USB charger

-

WIRELESS

-

3

-

Wireless charger

-
+| Name | Default Value | Description | +| -------- | ------------- | ---------------- | +| NONE | 0 | Unknown type | +| AC | 1 | AC charger | +| USB | 2 | USB charger | +| WIRELESS | 3 | Wireless charger | -## BatteryChargeState + +## BatteryChargeState Enumerates charging states. - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

NONE

-

0

-

Unknown state.

-

ENABLE

-

1

-

The battery is being charged.

-

DISABLE

-

2

-

The battery is not being charged.

-

FULL

-

3

-

The battery is fully charged.

-
+| Name | Default Value | Description | +| ------- | ------------- | --------------------------------- | +| NONE | 0 | Unknown state. | +| ENABLE | 1 | The battery is being charged. | +| DISABLE | 2 | The battery is not being charged. | +| FULL | 3 | The battery is fully charged. | + -## BatteryHealthState +## BatteryHealthState Enumerates battery health states. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

UNKNOWN

-

0

-

Unknown state.

-

GOOD

-

1

-

The battery is in the healthy state.

-

OVERHEAT

-

2

-

The battery is overheated.

-

OVERVOLTAGE

-

3

-

The battery voltage is over high.

-

COLD

-

4

-

The battery temperature is low.

-

DEAD

-

5

-

The battery is dead.

-
+| Name | Default Value | Description | +| ----------- | ------------- | ------------------------------------ | +| UNKNOWN | 0 | Unknown state. | +| GOOD | 1 | The battery is in the healthy state. | +| OVERHEAT | 2 | The battery is overheated. | +| OVERVOLTAGE | 3 | The battery voltage is over high. | +| COLD | 4 | The battery temperature is low. | +| DEAD | 5 | The battery is dead. | + 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 7a32f64231c3fde0e7b58d07b0a42f6b83ebe1f5..4f658d8880c014bdbc4cf46cd3ab1d2a7bb01ec0 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @@ -39,3 +39,4 @@ Provides the application information. | 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 apply for for the application. | 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 4b5437ad37fe5abe16948b4b88fd86567966c6a6..38a93fd67cb7cd086f4e2f317dfd9a966ddc1f6d 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @@ -53,7 +53,7 @@ Provides the detailed information of the permissions to request from the system. | name | string | Yes | Yes | Name of the permission to request. | | reason | string | Yes | Yes | Reason for requesting the permission. | | reasonId9+ | number | Yes | Yes | ID of the reason for requesting the permission.| -| usedScene | [UsedScene](#UsedScene) | Yes | Yes | Application scenario and timing for using the permission.| +| usedScene | [UsedScene](#usedscene) | Yes | Yes | Application scenario and timing for using the permission.| diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md index 7229bf0f4c6b812c6ec52d26c0d6f289858725e9..34b0ab6878da8b7a36848c5f7d7181022009a34b 100644 --- a/en/application-dev/reference/apis/js-apis-camera.md +++ b/en/application-dev/reference/apis/js-apis-camera.md @@ -175,6 +175,17 @@ cameraManager.getCameras().then((cameraArray) => { }) ``` +### Size + +Size parameters. This interface used to get supported size for Preview + Photo + Video. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Default Value | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ----------------------------------- | +| height | number | Yes | Desired height of the Preview + Photo + Video. | +| width | number | Yes | Desired width of the Preview + Photo + Video.| + ### createCameraInput createCameraInput(cameraId: string, callback: AsyncCallback): void @@ -249,7 +260,7 @@ Creates a **CameraInput** instance with the specified camera position and camera **Example** ``` -cameraManager.createCameraInput(cameraPosition, cameraType, (err, cameraInput) => { +cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED, (err, cameraInput) => { if (err) { console.error('Failed to create the CameraInput instance. ${err.message}'); return; @@ -282,7 +293,7 @@ Creates a **CameraInput** instance with the specified camera position and camera **Example** ``` -cameraManager.createCameraInput(cameraPosition, cameraType).then((cameraInput) => { +cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED).then((cameraInput) => { console.log('Promise returned with the CameraInput instance.'); }) ``` @@ -305,7 +316,11 @@ Listens for camera status changes. This API uses a callback to return the camera **Example** ``` -cameraManager.on('cameraStatus', (cameraStatusInfo) => { +cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { + if (err) { + console.error('Failed to get cameraStatus callback. ${err.message}'); + return; + } console.log('camera : ' + cameraStatusInfo.camera.cameraId); console.log('status: ' + cameraStatusInfo.status); }) @@ -327,14 +342,14 @@ After **[camera.getCameraManager](#cameragetcameramanager)** is called, a camera **Example** ``` -async function getCameraInfo() { +async function getCameraInfo("cameraId") { var cameraManager = await camera.getCameraManager(); var cameras = await cameraManager.getCameras(); var cameraObj = cameras[0]; var cameraId = cameraObj.cameraId; var cameraPosition = cameraObj.cameraPosition; var cameraType = cameraObj.cameraType; - var cameraId = cameraObj.connectionType; + var connectionType = cameraObj.connectionType; } ``` @@ -470,7 +485,7 @@ Checks whether a specified flash mode is supported. This API uses an asynchronou **Example** ``` -cameraInput.isFlashModeSupported(flashMode, (err, status) => { +cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { if (err) { console.error('Failed to check whether the flash mode is supported. ${err.message}'); return; @@ -502,7 +517,7 @@ Checks whether a specified flash mode is supported. This API uses a promise to r **Example** ``` -cameraInput.isFlashModeSupported(flashMode).then((status) => { +cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => { console.log('Promise returned with flash mode support status.' + status); }) ``` @@ -530,7 +545,7 @@ Before setting the parameters, do the following checks: **Example** ``` -cameraInput.setFlashMode(flashMode, (err) => { +cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { if (err) { console.error('Failed to set the flash mode ${err.message}'); return; @@ -567,7 +582,7 @@ Before setting the parameters, do the following checks: **Example** ``` -cameraInput.setFlashMode(flashMode).then(() => { +cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => { console.log('Promise returned with the successful execution of setFlashMode.'); }) ``` @@ -638,7 +653,7 @@ Checks whether a specified focus mode is supported. This API uses an asynchronou **Example** ``` -cameraInput.isFocusModeSupported(afMode, (err, status) => { +cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (err, status) => { if (err) { console.error('Failed to check whether the focus mode is supported. ${err.message}'); return; @@ -670,7 +685,7 @@ Checks whether a specified focus mode is supported. This API uses a promise to r **Example** ``` -cameraInput.isFocusModeSupported(afMode).then((status) => { +cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => { console.log('Promise returned with focus mode support status.' + status); }) ``` @@ -695,7 +710,7 @@ Before setting the focus mode, use **[isFocusModeSupported](#isfocusmodesupporte **Example** ``` -cameraInput.setFocusMode(afMode, (err) => { +cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => { if (err) { console.error('Failed to set the focus mode ${err.message}'); return; @@ -729,7 +744,7 @@ Before setting the focus mode, use **[isFocusModeSupported](#isfocusmodesupporte **Example** ``` -cameraInput.setFocusMode(afMode).then(() => { +cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => { console.log('Promise returned with the successful execution of setFocusMode.'); }) ``` @@ -848,7 +863,7 @@ Sets a zoom ratio. This API uses an asynchronous callback to return the result. **Example** ``` -cameraInput.setZoomRatio(zoomRatio, (err) => { +cameraInput.setZoomRatio(1, (err) => { if (err) { console.error('Failed to set the zoom ratio value ${err.message}'); return; @@ -880,7 +895,7 @@ Sets a zoom ratio. This API uses a promise to return the result. **Example** ``` -cameraInput.setZoomRatio(zoomRatio).then(() => { +cameraInput.setZoomRatio(1).then(() => { console.log('Promise returned with the successful execution of setZoomRatio.'); }) ``` @@ -950,7 +965,7 @@ Releases this **CameraInput** instance. This API uses an asynchronous callback t **Example** ``` -camera.release((err) => { +cameraInput.release((err) => { if (err) { console.error('Failed to release the CameraInput instance ${err.message}'); return; @@ -1027,6 +1042,27 @@ cameraInput.on('error', (cameraInputError) => { }) ``` +## CameraInputErrorCode + +Enumerates the CameraInput error code. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| ERROR_UNKNOWN | -1 | Unknown error.| + +## CameraInputError + +Camera input error object which extends **Error** interface. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| code | [CameraInputErrorCode](#camerainputerrorcode) | Used to get error code in CameraInput on('error') callback| ## FlashMode @@ -1836,6 +1872,28 @@ captureSession.on('error', (captureSessionError) => { }) ``` +## CaptureSessionErrorCode + +Enumerates the CaptureSession error code. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| ERROR_UNKNOWN | -1 | Unknown error.| + +## CaptureSessionError + +Capture session error object which extends **Error** interface. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| code | [CaptureSessionErrorCode](#capturesessionerrorcode) | Used to get error code in CaptureSession on('error') callback.| + ## camera.createPreviewOutput createPreviewOutput(surfaceId: string, callback: AsyncCallback): void @@ -1854,7 +1912,7 @@ Creates a **PreviewOutput** instance. This API uses an asynchronous callback to **Example** ``` -camera.createPreviewOutput((surfaceId), (err, previewOutput) => { +camera.createPreviewOutput(("surfaceId"), (err, previewOutput) => { if (err) { console.error('Failed to create the PreviewOutput instance. ${err.message}'); return; @@ -1886,7 +1944,7 @@ Creates a **PreviewOutput** instance. This API uses a promise to return the inst **Example** ``` -camera.createPreviewOutput(surfaceId).then((previewOutput) => { +camera.createPreviewOutput("surfaceId").then((previewOutput) => { console.log('Promise returned with the PreviewOutput instance'); }) ``` @@ -2013,6 +2071,28 @@ previewOutput.on('error', (previewOutputError) => { }) ``` +## PreviewOutputErrorCode + +Enumerates the PreviewOutput error code. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| ERROR_UNKNOWN | -1 | Unknown error.| + +## PreviewOutputError + +Preview output error object which extends **Error** interface. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | Used to get error code in PreviewOutput on('error') callback.| + ## camera.createPhotoOutput createPhotoOutput(surfaceId: string, callback: AsyncCallback): void @@ -2031,7 +2111,7 @@ Creates a **PhotoOutput** instance. This API uses an asynchronous callback to re **Example** ``` -camera.createPhotoOutput((surfaceId), (err, photoOutput) => { +camera.createPhotoOutput(("surfaceId"), (err, photoOutput) => { if (err) { console.error('Failed to create the PhotoOutput instance. ${err.message}'); return; @@ -2063,7 +2143,7 @@ Creates a **PhotoOutput** instance. This API uses a promise to return the instan **Example** ``` -camera.createPhotoOutput(surfaceId).then((photoOutput) => { +camera.createPhotoOutput("surfaceId").then((photoOutput) => { console.log('Promise returned with PhotoOutput instance'); }) ``` @@ -2260,7 +2340,7 @@ Listens for photo capture start events. This API uses a callback to return the e **Example** ``` -photoOutput.on('captureStart', (captureId) => { +photoOutput.on('captureStart', (err, captureId) => { console.log('photo capture stated, captureId : ' + captureId); }) ``` @@ -2336,6 +2416,50 @@ photoOutput.on('error', (photoOutputError) => { }) ``` +### FrameShutterInfo + +Frame shutter callback info which provides **captureId** & **timestamp** parameteres & indicates the frame shutter event. + +**Parameteres** + +| Name | Type | Mandatory| Description | +| :------- | :------------------------------- | :--- | :---------------------------------------- | +| captureId | number | Yes | Capture id.| +| timestamp | number | Yes | Timestamp for frame. + +### CaptureEndInfo + +Capture end info which provides **captureId** & **frameCount** parameteres & indicates the photo capture end event. + +**Parameteres** + +| Name | Type | Mandatory| Description | +| :------- | :------------------------------- | :--- | :---------------------------------------- | +| captureId | number | Yes | Capture id.| +| frameCount | number | Yes | Frame count. + +## PhotoOutputErrorCode + +Enumerates the PhotoOutput error code. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| ERROR_UNKNOWN | -1 | Unknown error.| + +## PhotoOutputError + +Photo output error object which extends **Error** interface. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| code | [PhotoOutputErrorCode](#photooutputerrorcode) | Used to get error code in PhotoOutput on('error') callback.| + ## camera.createVideoOutput createVideoOutput(surfaceId: string, callback: AsyncCallback): void @@ -2354,7 +2478,7 @@ Creates a **VideoOutput** instance. This API uses an asynchronous callback to re **Example** ``` -camera.createVideoOutput((surfaceId), (err, videoOutput) => { +camera.createVideoOutput(("surfaceId"), (err, videoOutput) => { if (err) { console.error('Failed to create the VideoOutput instance. ${err.message}'); return; @@ -2386,7 +2510,8 @@ Creates a **VideoOutput** instance. This API uses a promise to return the instan **Example** ``` -camera.createVideoOutput(surfaceId).then((videoOutput) => { +camera.createVideoOutput("surfaceId" +).then((videoOutput) => { console.log('Promise returned with the VideoOutput instance'); }) ``` @@ -2609,3 +2734,25 @@ videoOutput.on('error', (VideoOutputError) => { console.log('Video output error code: ' + VideoOutputError.code); }) ``` + +## VideoOutputErrorCode + +Enumerates the VideoOutput error code. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| ERROR_UNKNOWN | -1 | Unknown error.| + +## VideoOutputError + +Photo output error object which extends **Error** interface. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| code | [VideoOutputErrorCode](#videooutputerrorcode) | Used to get error code in VideoOutput on('error') callback.| \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-cardEmulation.md b/en/application-dev/reference/apis/js-apis-cardEmulation.md new file mode 100644 index 0000000000000000000000000000000000000000..3f0d063a7e435b2f777f79bb6934aaf8d233e13a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-cardEmulation.md @@ -0,0 +1,111 @@ +# Standard NFC Card Emulation + +Implements Near-Field Communication (NFC) card emulation. + +> **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** + +``` +import cardEmulation from '@ohos.nfc.cardEmulation'; +``` + + +## cardEmulation.isSupported + +isSupported(feature: number): boolean + +Checks whether a certain type of card emulation is supported. + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the card emulation is supported; returns **false** otherwise.| + +## HceService + +Implements Host-based Card Emulation (HCE). Before calling any API in **HceService**, you must use **new cardEmulation.HceService()** to create an **HceService** instance. + +### startHCE + +startHCE(aidList: string[]): boolean + +Starts HCE. + +**Required permissions**: ohos.permission.NFC_CARD_EMULATION + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------- | ---- | ----------------------- | +| aidList | string[] | Yes | Application ID (AID) list to be registered for card emulation.| + +### stopHCE + +stopHCE(): boolean + +Stops HCE. + +**Required permissions**: ohos.permission.NFC_CARD_EMULATION + +**System capability**: SystemCapability.Communication.NFC + +### on + +on(type: "hceCmd", callback: AsyncCallback): void; + +Subscribes to messages from the peer device after **startHCE()**. + +**Required permissions**: ohos.permission.NFC_CARD_EMULATION + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------------- | +| type | string | Yes | Event type to subscribe to. The value is **hceCmd**. | +| callback | AsyncCallback | Yes | Callback invoked to return the subscribed event. The input parameter is a data array that complies with the Application Protocol Data Unit (APDU).| + +### sendResponse + +sendResponse(responseApdu: number[]): void; + +Sends a response to the peer device. + +**Required permissions**: ohos.permission.NFC_CARD_EMULATION + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | -------- | ---- | -------------------------------------------------- | +| responseApdu | number[] | Yes | Data to send, which is an array that complies with the APDU.| + +**Example** + +```js +var hceService = new cardEmulation.HceService(); +hceService.startHCE([ + "F0010203040506", "A0000000041010" +]) +hceService.stopHCE(); +hceService.on("hceCmd", (err, res) => { + if(err.data === 0) { + console.log('callback => Operation hceCmd succeeded. Data: ' + JSON.stringify(res)); + hceService.sendResponse([0x00,0xa4,0x04,0x00, + 0x0e,0x32,0x50,0x41,0x59,0x2e,0x53,0x59,0x53,0x2e,0x44,0x44, + 0x46,0x30,0x31,0x00]); + } else { + console.log('callback => Operation hceCmd failed. Cause: ' + err.data); + } +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 0c9b2e2352cea78bbfa4b98b6a329af95133cf68..50c4228a23727b230a2ffab82dcf077be5f6682b 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -1,6 +1,6 @@ # CommonEvent -> ![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. ## Required Permissions @@ -181,7 +181,7 @@ Publishes a common event. This API uses a callback to return the result. **Example** ```js -// Callback for common event publication +// Callback for common event publication. function PublishCallBack(err) { if (err.code) { console.error("publish failed " + JSON.stringify(err)); @@ -219,7 +219,7 @@ Publishes a common event with given attributes. This API uses a callback to retu // Attributes of a common event. var options = { code: 0, // Result code of the common event - data: "initial data";// Result data of the common event + data: "initial data",// Result data of the common event isOrdered: true // The common event is an ordered one. } @@ -257,7 +257,7 @@ Publishes a common event to a specific user. This API uses a callback to return **Example** ```js -// Callback for common event publication +// Callback for common event publication. function PublishAsUserCallBack(err) { if (err.code) { console.error("publishAsUser failed " + JSON.stringify(err)); @@ -299,7 +299,7 @@ Publishes a common event with given attributes to a specific user. This API uses // Attributes of a common event. var options = { code: 0, // Result code of the common event - data: "initial data";// Result data of the common event + data: "initial data",// Result data of the common event } // Callback for common event publication @@ -1177,12 +1177,12 @@ Finishes this ordered common event. This API uses a callback to return the resul var subscriber; // Subscriber object successfully created. // Callback for ordered common event finishing. -function finishCommonEventCallback() { +function finishCommonEventCallback(err) { if (err.code) { - console.error("finishCommonEvent failed " + JSON.stringify(err)); - } else { - console.info("FinishCommonEvent"); - } + console.error("finishCommonEvent failed " + JSON.stringify(err)); +} else { + console.info("FinishCommonEvent"); +} } subscriber.finishCommonEvent(finishCommonEventCallback); ``` diff --git a/en/application-dev/reference/apis/js-apis-contact.md b/en/application-dev/reference/apis/js-apis-contact.md index e9ac02205ed355fb1a0933f449ebd9b304277adc..ee5cf3137c7aa5d1ef6cb8ef1c1ef47ef8b35236 100644 --- a/en/application-dev/reference/apis/js-apis-contact.md +++ b/en/application-dev/reference/apis/js-apis-contact.md @@ -195,7 +195,7 @@ Updates a contact based on the specified contact information and attributes. Thi fullName: {fullName: 'xxx'}, phoneNumbers: [{phoneNumber: '138xxxxxxxx'}] },{ - attributes:['ATTR_EMAIL', 'ATTR_NAME'] + attributes:[contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err) => { if (err) { console.log('updateContact callback: err->${JSON.stringify(err)}'); @@ -234,7 +234,7 @@ Updates a contact based on the specified contact information and attributes. Thi fullName: {fullName: 'xxx'}, phoneNumbers: [{phoneNumber: '138xxxxxxxx'}] }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }); promise.then(() => { console.log('updateContact success'); @@ -564,7 +564,9 @@ Queries contacts based on the specified key and application. This API uses an as ```js contact.queryContact('xxx', { - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, (err, data) => { if (err) { console.log(`queryContact callback: err->${JSON.stringify(err)}`); @@ -596,7 +598,7 @@ Queries contacts based on the specified key and attributes. This API uses an asy ```js contact.queryContact('xxx', { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryContact callback: err->${JSON.stringify(err)}`); @@ -630,8 +632,11 @@ Queries contacts based on the specified key, application, and attributes. This A ```js contact.queryContact('xxx', { holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryContact callback: err->${JSON.stringify(err)}`); @@ -669,8 +674,11 @@ Queries contacts based on the specified key, application, and attributes. This A ```js let promise = contact.queryContact('xxx', { holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }); promise.then((data) => { console.log(`queryContact success: data->${JSON.stringify(data)}`); @@ -728,7 +736,9 @@ Queries all contacts based on the specified application. This API uses an asynch ```js contact.queryContacts({ - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, (err, data) => { if (err) { console.log(`queryContacts callback: err->${JSON.stringify(err)}`); @@ -759,7 +769,7 @@ Queries all contacts based on the specified attributes. This API uses an asynchr ```js contact.queryContacts({ - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryContacts callback: err->${JSON.stringify(err)}`); @@ -791,9 +801,11 @@ Queries all contacts based on the specified application and attributes. This API ```js contact.queryContacts({ - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryContacts callback: err->${JSON.stringify(err)}`); @@ -829,9 +841,11 @@ Queries all contacts based on the specified application and attributes. This API ```js let promise = contact.queryContacts({ - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }); promise.then((data) => { console.log(`queryContacts success: data->${JSON.stringify(data)}`); @@ -891,7 +905,9 @@ Queries contacts based on the specified phone number and application. This API u ```js contact.queryContactsByPhoneNumber('138xxxxxxxx', { - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, (err, data) => { if (err) { console.log(`queryContactsByPhoneNumber callback: err->${JSON.stringify(err)}`); @@ -923,7 +939,7 @@ Queries contacts based on the specified phone number and attributes. This API us ```js contact.queryContactsByPhoneNumber('138xxxxxxxx', { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryContactsByPhoneNumber callback: err->${JSON.stringify(err)}`); @@ -956,9 +972,11 @@ Queries contacts based on the specified phone number, application, and attribute ```js contact.queryContactsByPhoneNumber('138xxxxxxxx', { - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryContactsByPhoneNumber callback: err->${JSON.stringify(err)}`); @@ -995,9 +1013,11 @@ Queries contacts based on the specified phone number, application, and attribute ```js let promise = contact.queryContactsByPhoneNumber('138xxxxxxxx', { - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }); promise.then((data) => { console.log(`queryContactsByPhoneNumber success: data->${JSON.stringify(data)}`); @@ -1057,7 +1077,9 @@ Queries contacts based on the specified email address and application. This API ```js contact.queryContactsByEmail('xxx@email.com', { - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, (err, data) => { if (err) { console.log(`queryContactsByEmail callback: err->${JSON.stringify(err)}`); @@ -1089,7 +1111,7 @@ Queries contacts based on the specified email address and attributes. This API u ```js contact.queryContactsByEmail('xxx@email.com', { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryContactsByEmail callback: err->${JSON.stringify(err)}`); @@ -1122,9 +1144,11 @@ Queries contacts based on the specified email address, application, and attribut ```js contact.queryContactsByEmail('xxx@email.com', { - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryContactsByEmail callback: err->${JSON.stringify(err)}`); @@ -1161,9 +1185,11 @@ Queries contacts based on the specified email address, application, and attribut ```js let promise = contact.queryContactsByEmail('xxx@email.com', { - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }); promise.then((data) => { console.log(`queryContactsByEmail success: data->${JSON.stringify(data)}`); @@ -1221,7 +1247,9 @@ Queries all groups of this contact based on the specified application. This API ```js contact.queryGroups({ - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, (err, data) => { if (err) { console.log(`queryGroups callback: err->${JSON.stringify(err)}`); @@ -1256,7 +1284,9 @@ Queries all groups of this contact based on the specified application. This API ```js let promise = contact.queryGroups({ - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }); promise.then((data) => { console.log(`queryGroups success: data->${JSON.stringify(data)}`); @@ -1371,7 +1401,9 @@ Queries the key of a contact based on the specified contact ID and application. ```js contact.queryKey(id, { - holderId:1 + holderId: 0, + bundleName: "", + displayName: "" }, (err, data) => { if (err) { console.log(`queryKey callback: err->${JSON.stringify(err)}`); @@ -1407,7 +1439,9 @@ Queries the key of a contact based on the specified contact ID and application. ```js let promise = contact.queryKey(id, { - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }); promise.then((data) => { console.log(`queryKey success: data->${JSON.stringify(data)}`); diff --git a/en/application-dev/reference/apis/js-apis-convertxml.md b/en/application-dev/reference/apis/js-apis-convertxml.md index 1b41a320c35d1c9295bdc3f830c731ccf83e0f27..3fd4e4e52ca7a82b33dd6a13aa7f425ab2aea9be 100644 --- a/en/application-dev/reference/apis/js-apis-convertxml.md +++ b/en/application-dev/reference/apis/js-apis-convertxml.md @@ -27,7 +27,7 @@ Converts an XML text into a JavaScript object. | Name | Type | Mandatory| Description | | ------- | --------------------------------- | ---- | --------------- | | xml | string | Yes | XML text to convert.| -| options | [ConvertOptions](#convertoptions) | No | Options for coversion. | +| options | [ConvertOptions](#convertoptions) | No | Options for conversion. | **Return value** @@ -57,7 +57,7 @@ console.log(result) ## ConvertOptions -Options for coversion. +Options for conversion. **System capability**: SystemCapability.Utils.Lang 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 bd14fac4882d454ba2f299ea811b89ed1d30167d..5e13507952dec34e32f7a4e49a75669ccc16fd82 100644 --- a/en/application-dev/reference/apis/js-apis-data-ability.md +++ b/en/application-dev/reference/apis/js-apis-data-ability.md @@ -1,6 +1,7 @@ # DataAbilityPredicates > **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. @@ -17,7 +18,7 @@ import dataAbility from '@ohos.data.dataAbility'; createRdbPredicates(name: string, dataAbilityPredicates: DataAbilityPredicates): rdb.RdbPredicates -Creates an **RdbPredicates** object based on a **DataAbilityPredicates** object. +Creates an **RdbPredicates** object from a **DataAbilityPredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -69,8 +70,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "lisi") + dataAbilityPredicates.equalTo("NAME", "lisi") ``` @@ -97,8 +97,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.notEqualTo("NAME", "lisi") + dataAbilityPredicates.notEqualTo("NAME", "lisi") ``` @@ -119,8 +118,7 @@ Adds a left parenthesis to this **DataAbilityPredicates**. **Example** ```js - let predicates = new dataAbilitylity.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "lisi") + dataAbilityPredicates.equalTo("NAME", "lisi") .beginWrap() .equalTo("AGE", 18) .or() @@ -146,8 +144,7 @@ Adds a right parenthesis to this **DataAbilityPredicates**. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "lisi") + dataAbilityPredicates.equalTo("NAME", "lisi") .beginWrap() .equalTo("AGE", 18) .or() @@ -173,8 +170,7 @@ Adds the OR condition to this **DataAbilityPredicates**. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Lisa") + dataAbilityPredicates.equalTo("NAME", "Lisa") .or() .equalTo("NAME", "Rose") ``` @@ -197,8 +193,7 @@ Adds the AND condition to this **DataAbilityPredicates**. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Lisa") + dataAbilityPredicates.equalTo("NAME", "Lisa") .and() .equalTo("SALARY", 200.5) ``` @@ -227,8 +222,7 @@ Sets a **DataAbilityPredicates** object to match a string containing the specifi **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.contains("NAME", "os") + dataAbilityPredicates.contains("NAME", "os") ``` @@ -255,8 +249,7 @@ Sets a **DataAbilityPredicates** object to match a string that starts with the s **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.beginsWith("NAME", "os") + dataAbilityPredicates.beginsWith("NAME", "os") ``` @@ -283,8 +276,7 @@ Sets a **DataAbilityPredicates** object to match a string that ends with the spe **Example** ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.endsWith("NAME", "se") + dataAbilityPredicates.endsWith("NAME", "se") ``` @@ -310,8 +302,7 @@ Sets a **DataAbilityPredicates** object to match the field whose value is null. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.isNull("NAME") + dataAbilityPredicates.isNull("NAME") ``` @@ -337,8 +328,7 @@ Sets a **DataAbilityPredicates** object to match the field whose value is not nu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.isNotNull("NAME") + dataAbilityPredicates.isNotNull("NAME") ``` @@ -365,8 +355,7 @@ Sets a **DataAbilityPredicates** object to match a string that is similar to the **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.like("NAME", "%os%") + dataAbilityPredicates.like("NAME", "%os%") ``` @@ -393,8 +382,7 @@ Sets a **DataAbilityPredicates** object to match the specified string. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.glob("NAME", "?h*g") + dataAbilityPredicates.glob("NAME", "?h*g") ``` @@ -422,8 +410,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.between("AGE", 10, 50) + dataAbilityPredicates.between("AGE", 10, 50) ``` @@ -451,8 +438,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.notBetween("AGE", 10, 50) + dataAbilityPredicates.notBetween("AGE", 10, 50) ``` @@ -479,8 +465,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.greaterThan("AGE", 18) + dataAbilityPredicates.greaterThan("AGE", 18) ``` @@ -507,8 +492,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.lessThan("AGE", 20) + dataAbilityPredicates.lessThan("AGE", 20) ``` @@ -535,8 +519,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.greaterThanOrEqualTo("AGE", 18) + dataAbilityPredicates.greaterThanOrEqualTo("AGE", 18) ``` @@ -563,8 +546,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.lessThanOrEqualTo("AGE", 20) + dataAbilityPredicates.lessThanOrEqualTo("AGE", 20) ``` @@ -590,8 +572,7 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.orderByAsc("NAME") + dataAbilityPredicates.orderByAsc("NAME") ``` @@ -617,8 +598,7 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.orderByDesc("AGE") + dataAbilityPredicates.orderByDesc("AGE") ``` @@ -639,14 +619,7 @@ Sets a **DataAbilityPredicates** object to filter out duplicate records. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Rose").distinct("NAME") - let promiseDistinct = rdbStore.query(predicates, ["NAME"]) - promiseDistinct.then((resultSet) => { - console.log("distinct") - }).catch((err) => { - expect(null).assertFail(); - }) + dataAbilityPredicates.equalTo("NAME", "Rose").distinct() ``` @@ -672,8 +645,7 @@ Set a **DataAbilityPredicates** object to specify the maximum number of records. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Rose").limitAs(3) + dataAbilityPredicates.equalTo("NAME", "Rose").limitAs(3) ``` @@ -699,8 +671,7 @@ Sets a **DataAbilityPredicates** object to specify the start position of the ret **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Rose").offsetAs(3) + dataAbilityPredicates.equalTo("NAME", "Rose").offsetAs(3) ``` @@ -726,8 +697,7 @@ Sets a **DataAbilityPredicates** object to group rows that have the same value i **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.groupBy(["AGE", "NAME"]) + dataAbilityPredicates.groupBy(["AGE", "NAME"]) ``` ### indexedBy @@ -751,8 +721,7 @@ Sets a **DataAbilityPredicates** object to specify the index column. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.indexedBy("SALARY_INDEX") + dataAbilityPredicates.indexedBy("SALARY_INDEX") ``` @@ -780,8 +749,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array< **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.in("AGE", [18, 20]) + dataAbilityPredicates.in("AGE", [18, 20]) ``` @@ -809,8 +777,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array< **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.notIn("NAME", ["Lisa", "Rose"]) + dataAbilityPredicates.notIn("NAME", ["Lisa", "Rose"]) ``` ## ValueType 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 1010a20849fb9da41e445bc5212e88427b3f28c5..73d27f9f20009d0674b4cf07e017139988d09fbe 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -1,6 +1,6 @@ # Preferences -Preferences provide capabilities for processing data in the form of key-value (KV) pairs and supports lightweight data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. +Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support lightweight data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. > **NOTE**
@@ -19,8 +19,8 @@ import data_preferences from '@ohos.data.preferences'; | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It is 80 bytes.| -| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It is 8192 bytes.| +| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It must be less than 80 bytes.| +| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It must be less than 8192 bytes.| ## data_preferences.getPreferences @@ -33,11 +33,11 @@ Reads a **Preferences** persistence file and loads data to the **Preferences** i **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| - | callback | AsyncCallback<[Preferences](#preferences)> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| +| name | string | Yes| Name of the **Preferences** instance persistence file.| +| callback | AsyncCallback<[Preferences](#preferences)> | Yes| Callback used to return the result.| **Example** ```ts @@ -60,15 +60,15 @@ Reads a **Preferences** persistence file and loads data to the **Preferences** i **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| +| name | string | Yes| Name of the **Preferences** instance persistence file.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[Preferences](#preferences)> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<[Preferences](#preferences)> | Promise used to return the result.| **Example** ```ts @@ -76,7 +76,7 @@ let promise = data_preferences.getPreferences(this.context, 'mystore') promise.then((preferences) => { console.info("Got preferences successfully.") }).catch((err) => { - console.info("Failed to get the preferences") + console.info("Failed to get the preferences") }) ``` @@ -91,11 +91,11 @@ Once a **Preferences** persistence file is deleted, the **Preferences** instance **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| +| name | string | Yes| Name of the **Preferences** instance persistence file.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts @@ -119,15 +119,15 @@ Once a **Preferences** persistence file is deleted, the **Preferences** instance **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| +| name | string | Yes| Name of the **Preferences** instance persistence file.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** ```ts @@ -151,11 +151,11 @@ When a **Preferences** singleton instance is removed, this instance cannot be us **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| +| name | string | Yes| Name of the **Preferences** instance persistence file.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts @@ -179,16 +179,16 @@ When a **Preferences** singleton instance is removed, this instance cannot be us **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| +| name | string | Yes| Name of the **Preferences** instance persistence file.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** ```ts @@ -215,15 +215,15 @@ Obtains the value of a key. If the value is null or a non-default value, the def **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data to obtain. It cannot be empty.| - | defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.| - | callback | AsyncCallback<ValueType> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the data to obtain. It cannot be empty.| +| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.| +| callback | AsyncCallback<ValueType> | Yes| Callback used to return the result.| **Example** ```ts - preferences.get('startup', 'default', function(err, value) { +preferences.get('startup', 'default', function(err, value) { if (err) { console.info("Failed to get the value of startup, err: " + err) return @@ -242,15 +242,15 @@ Obtains the value of a key. If the value is null or a non-default value, the def **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data to obtain. It cannot be empty.| - | defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the data to obtain. It cannot be empty.| +| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<ValueType> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<ValueType> | Promise used to return the result.| **Example** ```ts @@ -262,6 +262,57 @@ promise.then((value) => { }) ``` +### getAll + +getAll(callback: AsyncCallback<Object>): void; + +Obtains the **Object** instance that contains all KV pairs. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<Object> | Yes| Callback used to return the **Object** instance obtained.| + +**Example** +```ts +preferences.get.getAll(function (err, value) { + if (err) { + console.info("getAll failed, err: " + err) + return + } + let keys = Object.keys(value) + console.info('getAll keys = ' + keys) + console.info("getAll object = " + JSON.stringify(value)) +}); +``` + + +### getAll + +getAll(): Promise<Object> + +Obtains the **Object** instance that contains all KV pairs. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<Object> | Promise used to return the **Object** instance obtained.| + +**Example** +```ts +let promise = preferences.getAll() +promise.then((value) => { + let keys = Object.keys(value) + console.info('getAll keys = ' + keys) + console.info("getAll object = " + JSON.stringify(value)) +}).catch((err) => { + console.info("getAll failed, err: " + err) +}) +``` ### put @@ -272,11 +323,11 @@ Puts a new value to this **Preferences** instance and its persistence file. This **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the data. It cannot be empty.| +| value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts @@ -299,15 +350,15 @@ Puts a new value to this **Preferences** instance and its persistence file. This **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the data. It cannot be empty.| +| value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** ```ts @@ -322,22 +373,17 @@ promise.then(() => { ### has -has(key: string, callback: AsyncCallback<boolean>): boolean +has(key: string, callback: AsyncCallback<boolean>): void Checks whether this **Preferences** instance contains data with a given key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data to check. It cannot be empty.| - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| - -**Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the **Preferences** instance contains data with the specified key; returns **false** otherwise.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the data to check. It cannot be empty.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. It returns **true** if the **Preferences** instance contains data with the given key and returns **false** otherwise.| **Example** ```ts @@ -364,14 +410,14 @@ Checks whether this **Preferences** instance contains data with a given key. Thi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data to check. It cannot be empty.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the data to check. It cannot be empty.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. It returns **true** if the **Preferences** instance contains data with the given key and returns **false** otherwise.| **Example** ```ts @@ -383,7 +429,7 @@ promise.then((isExist) => { console.info("The key of startup is not contained.") } }).catch((err) => { - console.info("Check the key of startup failed, err: " + err) + console.info("Failed to check the key of startup, err: " + err) }) ``` @@ -397,10 +443,10 @@ Deletes a KV pair of the specified key from this **Preferences** instance. This **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the KV pair to delete. It cannot be empty.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the KV pair to delete. It cannot be empty.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts @@ -423,14 +469,14 @@ Deletes a KV pair of the specified key from this **Preferences** instance. This **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the KV pair to delete. It cannot be empty.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the KV pair to delete. It cannot be empty.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** ```ts @@ -452,9 +498,9 @@ Saves the modification to this **Preferences** instance and synchronizes the mod **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts @@ -477,9 +523,9 @@ Saves the modification to this **Preferences** instance and synchronizes the mod **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** ```ts @@ -500,10 +546,10 @@ Clears data of this **Preferences** instance. This API uses an asynchronous call **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts @@ -526,9 +572,9 @@ Clears data of this **Preferences** instance. This API uses a promise to return **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** ```ts @@ -550,10 +596,10 @@ Subscribes to data changes. When the value of the subscribed key changes, a call **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Description| - | -------- | -------- | -------- | - | type | string | Event type. The value **change** indicates data change events.| - | callback | Callback<{ key : string }> | Callback used to return data changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value **change** indicates data change events.| +| callback | Callback<{ key : string }> | Yes| Callback used to return data changes.| **Example** ```ts @@ -584,17 +630,17 @@ preferences.put('startup', 'auto', function (err) { ### off('change') -off(type: 'change', callback: Callback<{ key : string }>): void +off(type: 'change', callback?: Callback<{ key : string }>): void Unsubscribes from data changes. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Description| - | -------- | -------- | -------- | - | type | string | Event type. The value **change** indicates data change events.| - | callback | Callback<{ key : string }> | Callback used to return data changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value **change** indicates data change events.| +| callback | Callback<{ key : string }> | No| Callback used to return data changes. If this parameter is left empty, all callbacks for data changes will be canceled.| **Example** ```ts 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 f1211dc922a699081aeab7a5b145771923d8f7fe..86b5c39b48db3bbdd15de93bd3411e915c351135 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -75,7 +75,7 @@ promise.then(async (rdbStore) => { getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void -Obtains a relational database (RDB) store. This API uses an asynchronous callback to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. +Obtains a RDB store. This API uses an asynchronous callback to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -139,7 +139,7 @@ promise.then(async (rdbStore) => { deleteRdbStore(name: string, callback: AsyncCallback<void>): void -Deletes an RDB store. This API uses a callback to return the result. +Deletes an RDB store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -636,7 +636,7 @@ Sets the **RdbPredicates** to match the specified string. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| -| value | string | Yes| Value to match the **RdbPredicates**.

Wildcards are supported. ***** indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| +| value | string | Yes| Value to match the **RdbPredicates**.

Wildcards are supported. * indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| **Return value** | Type| Description| @@ -889,10 +889,10 @@ 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) + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) }).catch((err) => { - console.log("query err.") + console.log("Query err.") }) ``` @@ -1064,16 +1064,16 @@ Provides methods to manage an RDB store. ### insert -insert(name: string, values: ValuesBucket, callback: AsyncCallback<number>):void +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. +Inserts a row of data into a table. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the target table.| +| table | string | Yes| Name of the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.| | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| @@ -1097,7 +1097,7 @@ rdbStore.insert("EMPLOYEE", valueBucket, function (err, ret) { ### insert -insert(name: string, values: ValuesBucket):Promise<number> +insert(table: string, values: ValuesBucket):Promise<number> Inserts a row of data into a table. This API uses a promise to return the result. @@ -1106,7 +1106,7 @@ Inserts a row of data into a table. This API uses a promise to return the result **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the target table.| +| table | string | Yes| Name of the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.| **Return value** @@ -1133,17 +1133,17 @@ promise.then(async (ret) => { ### update -update(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void +update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void -Updates data in the database based on the specified RdbPredicates object. This API uses a callback to return the result. +Updates data in the database based on the specified RdbPredicates object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| values | [ValuesBucket](#valuesbucket) | Yes| Data to update. The value specifies the row of data to be updated in the database. The key-value pair is associated with the column name in the target table.| -| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Row of data to insert.| +| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| | callback | AsyncCallback<number> | Yes| Callback used to return the number of rows updated.| **Example** @@ -1168,7 +1168,7 @@ rdbStore.update(valueBucket, predicates, function (err, ret) { ### update -update(values: ValuesBucket, rdbPredicates: RdbPredicates):Promise<number> +update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> Updates data in the database based on the specified RdbPredicates object. This API uses a promise to return the result. @@ -1177,8 +1177,8 @@ Updates data in the database based on the specified RdbPredicates object. This A **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| values | [ValuesBucket](#valuesbucket) | Yes| Data to update. The value specifies the row of data to be updated in the database. The key-value pair is associated with the column name in the target table.| -| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Row of data to insert.| +| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| **Return value** | Type| Description| @@ -1203,20 +1203,92 @@ promise.then(async (ret) => { }) ``` +### update9+ +update(table: string, values: ValuesBucket, predicates: DataSharePredicates, callback: AsyncCallback<number>):void + +Updates data in the database based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| table | string | Yes| Name of the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| +| predicates | DataSharePredicates | Yes| Update conditions specified by the **DataSharePredicates** object.| +| callback | AsyncCallback<number> | Yes| Callback used to return the number of rows updated.| + +**Example** +```js +import dataShare from '@ohos.data.dataShare' +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new dataShare.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { + if (err) { + console.info("Failed to update data, err: " + err) + return + } + console.log("Updated row count: " + ret) +}) +``` +### update9+ + +update(table: string, values: ValuesBucket, predicates: DataSharePredicates):Promise<number> + +Updates data in the database based on the specified **DataSharePredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| table | string | Yes| Name of the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| +| predicates | DataSharePredicates | Yes| Update conditions specified by the **DataSharePredicates** object.| + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the number of rows updated.| + +**Example** +```js +import dataShare from '@ohos.data.dataShare' +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new dataShare.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.update("EMPLOYEE", valueBucket, predicates) +promise.then(async (ret) => { + console.log("Updated row count: " + ret) +}).catch((err) => { + console.info("Failed to update data, err: " + err) +}) +``` ### delete -delete(rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void +delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void -Deletes data from the database based on the specified RdbPredicates object. This API uses a callback to return the result. +Deletes data from the database based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified for deleting data.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified by the **RdbPredicates** object for deleting data.| | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| **Example** @@ -1235,16 +1307,16 @@ rdbStore.delete(predicates, function (err, rows) { ### delete -delete(rdbPredicates: RdbPredicates):Promise<number> +delete(predicates: RdbPredicates):Promise<number> -Deletes data from the database based on the specified RdbPredicates object. This API uses a promise to return the result. +Deletes data from the database based on the specified **RdbPredicates** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified for deleting data.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified by the **RdbPredicates** object for deleting data.| **Return value** | Type| Description| @@ -1263,19 +1335,79 @@ promise.then((rows) => { }) ``` +### delete9+ + +delete(table: string, predicates: DataSharePredicates, callback: AsyncCallback<number>):void + + +Deletes data from the database based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| table | string | Yes| Name of the target table.| +| predicates | 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** +```js +import dataShare from '@ohos.data.dataShare' +let predicates = new dataShare.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { + if (err) { + console.info("Failed to delete data, err: " + err) + return + } + console.log("Delete rows: " + rows) +}) +``` +### delete9+ + +delete(table: string, predicates: DataSharePredicates):Promise<number> + +Deletes data from the database based on the specified **DataSharePredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| table | string | Yes| Name of the target table.| +| predicates | 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.| + +**Example** +```js +import dataShare from '@ohos.data.dataShare' +let predicates = new dataShare.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.delete("EMPLOYEE", predicates) +promise.then((rows) => { + console.log("Delete rows: " + rows) +}).catch((err) => { + console.info("Failed to delete data, err: " + err) +}) +``` ### query -query(rdbPredicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void +query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void -Queries data in the database based on specified conditions. This API uses a callback to return the result. +Queries data in the database based on specified conditions. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** 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.| @@ -1288,15 +1420,15 @@ rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (e console.info("Query failed, err: " + err) return } - console.log("resultSet column names:" + resultSet.columnNames) - console.log("resultSet column count:" + resultSet.columnCount) + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) }) ``` ### query -query(rdbPredicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> +query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> Queries data in the database based on specified conditions. This API uses a promise to return the result. @@ -1305,7 +1437,7 @@ Queries data in the database based on specified conditions. This API uses a prom **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| | columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| **Return value** @@ -1319,19 +1451,81 @@ Queries data in the database based on specified conditions. This API uses a prom predicates.equalTo("NAME", "Rose") let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) promise.then((resultSet) => { - console.log("resultSet column names:" + resultSet.columnNames) - console.log("resultSet column count:" + resultSet.columnCount) + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) }).catch((err) => { console.info("Query failed, err: " + err) }) ``` +### query9+ + +query(predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void + +Queries data in the database based on specified conditions. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| predicates | 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.| + +**Example** +```js +import dataShare from '@ohos.data.dataShare' +let predicates = new dataShare.DataSharePredicates() +predicates.equalTo("NAME", "Rose") +rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { + if (err) { + console.info("Query failed, err: " + err) + return + } + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### query9+ + +query(predicates: DataSharePredicates, columns?: Array<string>):Promise<ResultSet> + +Queries data in the database based on specified conditions. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| predicates | 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** +| Type| Description| +| -------- | -------- | +| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** +```js +import dataShare from '@ohos.data.dataShare' +let predicates = new dataShare.DataSharePredicates() +predicates.equalTo("NAME", "Rose") +let promise = rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSet) => { + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Query failed, err: " + err) +}) +``` ### querySql8+ querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void -Queries data in the RDB store using the specified SQL statement. This API uses a callback to return the result. +Queries data in the RDB store using the specified SQL statement. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1349,8 +1543,8 @@ rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", console.info("Query failed, err: " + err) return } - console.log("resultSet column names:" + resultSet.columnNames) - console.log("resultSet column count:" + resultSet.columnCount) + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) }) ``` @@ -1378,8 +1572,8 @@ Queries data in the RDB store using the specified SQL statement. This API uses a ```js let promise = rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) promise.then((resultSet) => { - console.log("resultSet column names:" + resultSet.columnNames) - console.log("resultSet column count:" + resultSet.columnCount) + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) }).catch((err) => { console.info("Query failed, err: " + err) }) @@ -1390,7 +1584,7 @@ promise.then((resultSet) => { executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void -Runs the SQL statement that contains the specified parameters but does not return a value. This API uses a callback to return the execution result. +Runs the SQL statement that contains the specified parameters but does not return a value. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1406,10 +1600,10 @@ Runs the SQL statement that contains the specified parameters but does not retur const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { if (err) { - console.info("executeSql failed, err: " + err) + console.info("ExecuteSql failed, err: " + err) return } - console.info('create table done.') + console.info('Create table done.') }) ``` @@ -1438,7 +1632,7 @@ Runs the SQL statement that contains the specified parameters but does not retur const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" let promise = rdbStore.executeSql(SQL_CREATE_TABLE) promise.then(() => { - console.info('create table done.') + console.info('Create table done.') }).catch((err) => { console.info("ExecuteSql failed, err: " + err) }) @@ -1533,12 +1727,119 @@ try { } ``` +### backup9+ + +backup(destName:string, callback: AsyncCallback<void>):void + +Backs up the database with the specified name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| destName | string | Yes| Name of the database backup file.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| + +**Example** +```js +rdbStore.backup("dbBackup.db", function(err) { + if (err) { + console.info('Backup failed, err: ' + err) + return + } + console.info('Backup success.') +}) +``` + +### backup9+ + +backup(destName:string): Promise<void> + +Backs up the database with the specified name. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| destName | string | Yes| Name of the database backup file.| + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** +```js +let promiseBackup = rdbStore.backup("dbBackup.db") +promiseBackup.then(()=>{ + console.info('Backup success.') +}).catch((err)=>{ + console.info('Backup failed, err: ' + err) +}) +``` + +### restore9+ + +restore(srcName:string, callback: AsyncCallback<void>):void + +Restores a database from a specified database backup file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| srcName | string | Yes| Name of the database backup file.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| + +**Example** +```js +rdbStore.restore("dbBackup.db", function(err) { + if (err) { + console.info('Restore failed, err: ' + err) + return + } + console.info('Restore success.') +}) +``` + +### restore9+ + +restore(srcName:string): Promise<void> + +Restores a database from a specified database backup file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| srcName | string | Yes| Name of the database backup file.| + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** +```js +let promiseRestore = rdbStore.restore("dbBackup.db") +promiseRestore.then(()=>{ + console.info('Restore success.') +}).catch((err)=>{ + console.info('Restore failed, err: ' + err) +}) +``` ### setDistributedTables8+ setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void -Sets a list of distributed tables. This API uses a callback to return the result. +Sets a list of distributed tables. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1552,10 +1853,10 @@ Sets a list of distributed tables. This API uses a callback to return the result ```js rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { if (err) { - console.info('setDistributedTables failed, err: ' + err) + console.info('Failed to set distributed tables, err: ' + err) return } - console.info('setDistributedTables successful.') + console.info('Set distributed tables successfully.') }) ``` @@ -1566,6 +1867,8 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { Sets a list of distributed tables. This API uses a promise to return the result. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -1582,9 +1885,9 @@ Sets a list of distributed tables. This API uses a promise to return the result. ```js let promise = rdbStore.setDistributedTables(["EMPLOYEE"]) promise.then(() => { - console.info("setDistributedTables successful.") + console.info("Set distributed tables successfully.") }).catch((err) => { - console.info("setDistributedTables failed, err: " + err) + console.info("Failed to set distributed tables, err: " + err) }) ``` @@ -1592,7 +1895,9 @@ promise.then(() => { obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void -Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This API uses a callback to return the result. +Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1607,10 +1912,10 @@ Obtains the distributed table name for a remote device based on the local table ```js rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableName) { if (err) { - console.info('obtainDistributedTableName failed, err: ' + err) + console.info('Failed to obtain distributed table name, err: ' + err) return } - console.info('obtainDistributedTableName successful, tableName=.' + tableName) + console.info('Obtained distributed table name successfully, tableName=.' + tableName) }) ``` @@ -1621,6 +1926,8 @@ rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableNa Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This API uses a promise to return the result. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -1638,9 +1945,9 @@ Obtains the distributed table name for a remote device based on the local table ```js let promise = rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE") promise.then((tableName) => { - console.info('obtainDistributedTableName successful, tableName=' + tableName) + console.info('Obtained distributed table name successfully, tableName= ' + tableName) }).catch((err) => { - console.info('obtainDistributedTableName failed, err: ' + err) + console.info('Failed to obtain distributed table name, err: ' + err) }) ``` @@ -1648,7 +1955,9 @@ promise.then((tableName) => { sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array<[string, number]>>): void -Synchronizes data between devices. This API uses a callback to return the result. +Synchronizes data between devices. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1665,10 +1974,10 @@ let predicates = new rdb.RdbPredicates('EMPLOYEE') predicates.inDevices(['12345678abcde']) rdbStore.sync(rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { if (err) { - console.log('sync failed, err: ' + err) + console.log('Sync failed, err: ' + err) return } - console.log('sync done.') + console.log('Sync done.') for (let i = 0; i < result.length; i++) { console.log('device=' + result[i][0] + ' status=' + result[i][1]) } @@ -1682,6 +1991,8 @@ rdbStore.sync(rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { Synchronizes data between devices. This API uses a promise to return the result. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -1702,12 +2013,12 @@ let predicates = new data_rdb.RdbPredicates('EMPLOYEE') predicates.inDevices(['12345678abcde']) let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates) promise.then((result) =>{ - console.log('sync done.') + console.log('Sync done.') for (let i = 0; i < result.length; i++) { console.log('device=' + result[i][0] + ' status=' + result[i][1]) } }).catch((err) => { - console.log('sync failed') + console.log('Sync failed') }) ``` @@ -1717,6 +2028,8 @@ on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<stri Registers an observer for this RDB store. When the data in the RDB store changes, a callback is invoked to return the data changes. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -1747,6 +2060,8 @@ off(event:'dataChange', type: SubscribeType, observer: Callback<Array<stri Deletes the specified observer of the RDB store. This API uses a callback to return the result. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -1821,6 +2136,8 @@ Defines the database synchronization mode. Defines the subscription type. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | Name | Default Value| Description| 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 63ae9d95bc7da1a827030de4e644d44d68c7235c..6cdfcf94fdf36dd3f9d4adb4e44420394120fd10 100644 --- a/en/application-dev/reference/apis/js-apis-data-storage.md +++ b/en/application-dev/reference/apis/js-apis-data-storage.md @@ -22,15 +22,15 @@ import dataStorage from '@ohos.data.storage'; | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It is 80 bytes.| -| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It is 8192 bytes.| +| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It must be less than 80 bytes.| +| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It must be less than 8192 bytes.| ## dataStorage.getStorageSync getStorageSync(path: string): Storage -Reads the specified file and load its data to the **Storage** instance for data operations. +Reads the specified file and loads its data to the **Storage** instance for data operations. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core diff --git a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md index 1ce0a05d1ef3c97b9c0dd6d53c6abf22c2ec670c..df69b38be754f255ce637249c18a9d2fca5e13fd 100644 --- a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md +++ b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md @@ -1,7 +1,9 @@ -# DataAbilityHelper Module (JavaScript SDK APIs) +# DataAbilityHelper -> **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. +> The APIs of this module can be used only in the FA model. ## Modules to Import @@ -571,7 +573,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** @@ -870,7 +872,7 @@ DAHelper.query( ## DataAbilityHelper.call -call(uri: string, method: string, arg: string, extras: PacMap): Promise +call(uri: string, method: string, arg: string, extras: PacMap): Promise\ Calls the extended API of the Data ability. This API uses a promise to return the result. @@ -889,7 +891,7 @@ Calls the extended API of the Data ability. This API uses a promise to return th | Type| Description| |------ | ------- | -|Promise<[PacMap](#pacmap)> | Promise used to return the result.| +|Promise\<[PacMap](#pacmap)> | Promise used to return the result.| **Example** @@ -906,7 +908,7 @@ dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", " ## DataAbilityHelper.call -call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCallback): void +call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCallback\): void Calls the extended API of the Data ability. This API uses an asynchronous callback to return the result. @@ -920,7 +922,7 @@ Calls the extended API of the Data ability. This API uses an asynchronous callba | method | string | Yes | Name of the API to call. | | arg | string | Yes |Parameter to pass. | | extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | -| callback | AsyncCallback<[PacMap](#pacmap)> | Yes| Callback used to return the result. | +| callback | AsyncCallback\<[PacMap](#pacmap)> | Yes| Callback used to return the result. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-deque.md b/en/application-dev/reference/apis/js-apis-deque.md index b16ecfe75ea6ea083c5ff3bed796ebada1e06c58..8d9a9c1b42bef6ce74fdfb21a8033b80e68c1868 100644 --- a/en/application-dev/reference/apis/js-apis-deque.md +++ b/en/application-dev/reference/apis/js-apis-deque.md @@ -1,26 +1,32 @@ # Linear Container Deque -> ![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. +Double-ended queue (deque) is a sequence container implemented based on the queue data structure that follows the principles of First In First Out (FIFO) and Last In First Out (LIFO). It allows insertion and removal of elements at both the ends. **Deque** can dynamically adjust the capacity based on project requirements. It doubles the capacity each time. **Deque** differs from **[Queue](js-apis-queue.md)** and **[Vector](js-apis-vector.md)** mainly in the following aspects: + +**Queue** follows the principle of FIFO only and allows element removal at the front and insertion at the rear. + +**Vector** supports insertion and deletion of elements in between, as well asat both the ends. When compared with **Vector**, **Deque** is more efficient in inserting and removing header elements, but less efficient in accessing elements. + +**Recommended use case**: Use **Deque** when you need to frequently insert or remove elements at both the ends of a container. ## Modules to Import ```ts -import Deque from '@ohos.util.Deque' +import Deque from '@ohos.util.Deque'; ``` -## System Capabilities - -SystemCapability.Utils.Lang - ## Deque ### Attributes +**System capability**: SystemCapability.Utils.Lang + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Number of entries in a double-ended queue (deque, called container later).| +| length | number | Yes| No| Number of elements in a deque (called container later).| ### constructor @@ -28,6 +34,8 @@ constructor() A constructor used to create a **Deque** instance. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -38,13 +46,15 @@ let deque = new Deque(); insertFront(element: T): void -Inserts an entry at the front of this container. +Inserts an element at the front of this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to insert.| +| element | T | Yes| Target element.| **Example** @@ -62,13 +72,15 @@ deque.insertFront(false); insertEnd(element: T): void -Inserts an entry at the end of this container. +Inserts an element at the end of this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to insert.| +| element | T | Yes| Target element.| **Example** @@ -86,19 +98,21 @@ deque.insertEnd(false); has(element: T): boolean -Checks whether this container has the specified entry. +Checks whether this container has the specified element. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to check.| +| element | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the specified entry is contained; returns **false** otherwise.| +| boolean | Returns **true** if the specified element is contained; returns **false** otherwise.| **Example** @@ -113,13 +127,15 @@ let result1 = deque.has("Ahfbrgrbgnutfodgorrogorg"); popFirst(): T -Removes the first entry of this container. +Removes the first element of this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Type| Description| | -------- | -------- | -| T | Entry removed.| +| T | Element removed.| **Example** @@ -137,13 +153,15 @@ let result = deque.popFirst(); popLast(): T -Removes the last entry of this container. +Removes the last element of this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Type| Description| | -------- | -------- | -| T | Entry removed.| +| T | Element removed.| **Example** @@ -162,13 +180,15 @@ let result = deque.popLast(); forEach(callbackfn: (value: T, index?: number, deque?: Deque<T>) => void, thisArg?: Object): void -Uses a callback to traverse the entries in this container and obtain their position indexes. +Uses a callback to traverse the elements in this container and obtain their position indexes. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.| +| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -176,7 +196,7 @@ callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the element that is currently traversed.| -| index | number | No| Position index of the entry that is currently traversed.| +| index | number | No| Position index of the element that is currently traversed.| | deque | Deque<T> | No| Instance that invokes the **forEach** method.| **Example** @@ -188,7 +208,7 @@ deque.insertEnd(4); deque.insertFront(5); deque.insertEnd(4); deque.forEach((value, index) => { - console.log(value, index); + console.log("value:" + value, index); }); ``` @@ -196,13 +216,15 @@ deque.forEach((value, index) => { getFirst(): T -Obtains the first entry of this container. +Obtains the first element of this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Type| Description| | -------- | -------- | -| T | Entry obtained.| +| T | Element obtained.| **Example** @@ -219,13 +241,15 @@ let result = deque.getFirst(); getLast(): T -Obtains the last entry of this container. +Obtains the last element of this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Type| Description| | -------- | -------- | -| T | Entry obtained.| +| T | Element obtained.| **Example** @@ -242,9 +266,10 @@ let result = deque.getLast(); [Symbol.iterator]\(): IterableIterator<T> - Obtains an iterator, each item of which is a JavaScript object. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -261,14 +286,14 @@ deque.insertFront(4); // Method 1: for (let item of deque) { - console.log(item); + console.log("value:" + item); } // Method 2: let iter = deque[Symbol.iterator](); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value:" + temp); temp = iter.next().value; } ``` diff --git a/en/application-dev/reference/apis/js-apis-device-info.md b/en/application-dev/reference/apis/js-apis-device-info.md index 0f5dd2a794e92690820f12d6ab8e82e9f6b3b340..c23ee9f6eaccd02c06f9723a6544c61b2d821acb 100644 --- a/en/application-dev/reference/apis/js-apis-device-info.md +++ b/en/application-dev/reference/apis/js-apis-device-info.md @@ -1,6 +1,6 @@ # Device Information -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. ## Modules to Import @@ -24,7 +24,7 @@ import deviceInfo from '@ohos.deviceInfo' | softwareModel | string | Yes| No| Software model.| | hardwareModel | string | Yes| No| Hardware model.| | hardwareProfile | string | Yes| No| Hardware profile.| -| serial | string | Yes| No| Device serial number.| +| serial | string | Yes| No| Device serial number.
**Required permissions**: ohos.permission.sec.ACCESS_UDID (a system permission)| | bootloaderVersion | string | Yes| No| Bootloader version.| | abiList | string | Yes| No| Application binary interface (Abi) list.| | securityPatchTag | string | Yes| No| Security patch tag.| @@ -44,4 +44,4 @@ import deviceInfo from '@ohos.deviceInfo' | buildHost | string | Yes| No| Build host.| | buildTime | string | Yes| No| Build time.| | buildRootHash | string | Yes| No| Build root hash.| -| udid7+ | string | Yes| No| Device UDID.| +| udid7+ | string | Yes| No| Device UDID.
**Required permissions**: ohos.permission.sec.ACCESS_UDID (a system permission)| diff --git a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md index 11739fc75ed2e39a24f55c50a46a02bab94cd7d5..2ae6d7b5a18696850e13d8d088f9a1300561742c 100644 --- a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @@ -1,7 +1,7 @@ # Device Usage Statistics -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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 @@ -14,16 +14,16 @@ import bundleState from '@ohos.bundleState' isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void -Checks whether the application specified by **bundleName** is in the idle state. This API uses an asynchronous callback to return the result. +Checks whether the application specified by **bundleName** is in the idle state. This API uses an asynchronous callback to return the result. A third-party application can only check the idle status of itself. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns whether the application specified by **bundleName** is in the idle state if the value of **bundleName** is valid; returns **null** otherwise.| +| 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.| **Example** @@ -41,21 +41,21 @@ Checks whether the application specified by **bundleName** is in the idle state. isIdleState(bundleName: string): Promise<boolean> -Checks whether the application specified by **bundleName** is in the idle state. This API uses a promise to return the result. +Checks whether the application specified by **bundleName** is in the idle state. This API uses a promise to return the result. A third-party application can only check the idle status of itself. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | -------------- | +| bundleName | string | Yes | Bundle name of an application.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<boolean> | Promise used to return the result. Returns whether the application specified by **bundleName** is in the idle state if the value of **bundleName** is valid; returns **null** otherwise.| +| Type | Description | +| ---------------------- | ---------------------------------------- | +| Promise<boolean> | Promise used to return the result. If the value of **bundleName** is valid, **null** will be returned.| **Example** @@ -69,53 +69,62 @@ Checks whether the application specified by **bundleName** is in the idle state. ## bundleState.queryAppUsagePriorityGroup -queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void +queryAppUsagePriorityGroup(): Promise\ -Queries the priority group of the current invoker application. This API uses an asynchronous callback to return the result. +Queries the priority group of this application. This API uses a promise to return the result. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup -**Parameters** +**Return value** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<number> | Yes| Callback used to return the result.| +| Type | Description | +| --------------- | --------------------------- | +| Promise\ | Promise used to return the result.| **Example** - ```js - bundleState.queryAppUsagePriorityGroup((err, res) => { - if (err) { - console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failed. because: ' + err.code); - } else { - console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res)); - } - }); - ``` +```javascript +bundleState.queryAppUsagePriorityGroup().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); +}); +``` ## bundleState.queryAppUsagePriorityGroup -queryAppUsagePriorityGroup(): Promise<number> +queryAppUsagePriorityGroup(callback: AsyncCallback\): void -Queries the priority group of the current invoker application. This API uses a promise to return the result. +Queries the priority group of this application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup -**Return value** +**Parameters** -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | -------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** - ```js - bundleState.queryAppUsagePriorityGroup().then( res => { - console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res)); - }).catch( err => { - console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code); - }); - ``` +```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); + } else { + console.log('BUNDLE_ACTIVE QueryPackageGroup callback succeeded. result: ' + JSON.stringify(res)); + } +}); +``` ## bundleState.queryBundleStateInfos @@ -127,13 +136,15 @@ Queries the application usage duration statistics based on the specified start t **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| begin | number | Yes| Start time.| -| end | number | Yes| End time.| -| callback | AsyncCallback<[BundleActiveInfoResponse](#bundleactiveinforesponse)> | Yes| Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------------- | +| begin | number | Yes | Start time. | +| end | number | Yes | End time. | +| callback | AsyncCallback<[BundleActiveInfoResponse](#bundleactiveinforesponse)> | Yes | Callback used to return the result.| **Example** @@ -163,17 +174,19 @@ Queries the application usage duration statistics based on the specified start t **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| begin | number | Yes| Start time.| -| end | number | Yes| End time.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| begin | number | Yes | Start time.| +| end | number | Yes | End time.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ---------------------------------------- | -------------------------------------- | | Promise<[BundleActiveInfoResponse](#bundleactiveinforesponse)> | Promise used to return the result.| **Example** @@ -202,14 +215,16 @@ Queries the application usage duration statistics in the specified time frame at **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| byInterval | [IntervalType](#intervaltype) | Yes| Interval type.| -| begin | number | Yes| Start time.| -| end | number | Yes| End time.| -| callback | AsyncCallback<Array<[BundleStateInfo](#bundlestateinfo)>> | Yes| Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------------------- | ---- | ---------------------------------------- | +| byInterval | [IntervalType](#intervaltype) | Yes | Type of information to be queried. | +| begin | number | Yes | Start time. | +| end | number | Yes | End time. | +| callback | AsyncCallback<Array<[BundleStateInfo](#bundlestateinfo)>> | Yes | Callback used to return the result.| **Example** @@ -237,18 +252,20 @@ Queries the application usage duration statistics in the specified time frame at **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| byInterval | [IntervalType](#intervaltype) | Yes| Interval type.| -| begin | number | Yes| Start time.| -| end | number | Yes| End time.| +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------- | ---- | ----- | +| byInterval | [IntervalType](#intervaltype) | Yes | Type of information to be queried.| +| begin | number | Yes | Start time.| +| end | number | Yes | End time.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ---------------------------------------- | ---------------------------------------- | | Promise<Array<[BundleStateInfo](#bundlestateinfo)>> | Promise used to return the result.| **Example** @@ -275,13 +292,15 @@ Queries events of all applications based on the specified start time and end tim **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| begin | number | Yes| Start time.| -| end | number | Yes| End time.| -| callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | Yes| Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------------- | +| begin | number | Yes | Start time. | +| end | number | Yes | End time. | +| callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | Yes | Callback used to return the result.| **Example** @@ -309,17 +328,19 @@ Queries events of all applications based on the specified start time and end tim **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| begin | number | Yes| Start time.| -| end | number | Yes| End time.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| begin | number | Yes | Start time.| +| end | number | Yes | End time.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ---------------------------------------- | -------------------------------------- | | Promise<Array<[BundleActiveState](#bundleactivestate)>> | Promise used to return the result.| **Example** @@ -346,11 +367,11 @@ Queries events of this application based on the specified start time and end tim **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| begin | number | Yes| Start time.| -| end | number | Yes| End time.| -| callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | Yes| Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------------- | +| begin | number | Yes | Start time. | +| end | number | Yes | End time. | +| callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | Yes | Callback used to return the result.| **Example** @@ -378,15 +399,15 @@ Queries events of this application based on the specified start time and end tim **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| begin | number | Yes| Start time.| -| end | number | Yes| End time.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| begin | number | Yes | Start time.| +| end | number | Yes | End time.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ---------------------------------------- | -------------------------------------- | | Promise<Array<[BundleActiveState](#bundleactivestate)>> | Promise used to return the result.| **Example** @@ -413,22 +434,24 @@ Obtains the number of FA usage records specified by **maxNum**. This API uses a **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| maxNum | number | No| Maximum number of returned records. The maximum and default value is **1000**. If this parameter is not specified, **1000** is used.| +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------------- | +| maxNum | number | No | Maximum number of returned records. The maximum and default value is **1000**. If this parameter is not specified, **1000** is used.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ---------------------------------------- | ---------------------------------- | | Promise<Array<[BundleActiveModuleInfo](#bundleactivemoduleinfo9)>> | Promise used to return the result.| **Example** ```js - bundleState.getRecentlyUsedModules(this.maxNum).then( res => { + bundleState.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)); @@ -460,17 +483,19 @@ Obtains the number of FA usage records specified by **maxNum**. This API uses an **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| maxNum | number | No| Maximum number of returned records. The maximum and default value is **1000**. If this parameter is not specified, **1000** is used.| -| callback | AsyncCallback<Array<[BundleActiveModuleInfo](#bundleactivemoduleinfo9)>> | Yes| Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------------------- | +| maxNum | number | No | Maximum number of returned records. The maximum and default value is **1000**. If this parameter is not specified, **1000** is used. | +| callback | AsyncCallback<Array<[BundleActiveModuleInfo](#bundleactivemoduleinfo9)>> | Yes | Callback used to return the result.| **Example** ```js - bundleState.getRecentlyUsedModules(this.maxNum,(err, res) => { + bundleState.getRecentlyUsedModules(1000,(err, res) => { if(err) { console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code); } else { @@ -483,7 +508,7 @@ Obtains the number of FA usage records specified by **maxNum**. This API uses an }); // Invocation when maxNum is not passed - stats.getRecentlyUsedModules((err, res) => { + bundleState.getRecentlyUsedModules((err, res) => { if(err) { console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code); } else { @@ -496,59 +521,507 @@ Obtains the number of FA usage records specified by **maxNum**. This API uses an }); ``` +## bundleState.queryAppUsagePriorityGroup9+ + +queryAppUsagePriorityGroup(bundleName? : string): Promise + +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. + +**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO + +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + +**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 the target application. If this parameter is not specified, the priority group of the current application is queried.| + +**Return value** + +| Type | Description | +| --------------- | --------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```javascript +// Promise with bundleName +bundleState.queryAppUsagePriorityGroup(this.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); +}); +// Promise without bundleName +bundleState.queryAppUsagePriorityGroup().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); +}); +``` + +## bundleState.queryAppUsagePriorityGroup9+ + +queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback\): 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. + +**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO + +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + +**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 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. | + +**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); + } else { + console.log('BUNDLE_ACTIVE QueryPackageGroup callback succeeded. result: ' + JSON.stringify(res)); + } +}); +``` + +## bundleState.setBundleGroup9+ + +setBundleGroup(bundleName: string, newGroup: GroupType): Promise\ + +Sets the group for the application specified by **bundleName**. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO + +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + +**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 the target application.| +| newGroup | GroupType | Yes | Application group.| + +**Return value** + +| Type | Description | +| ------------- | ------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```javascript +this.bundleName = "com.example.deviceUsageStatistics"; +this.newGroup = stats.GroupType.ACTIVE_GROUP_DAILY; + +bundleState.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); +}); +``` + +## bundleState.setBundleGroup9+ + +setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback\): void + +Sets the group for the application specified by **bundleName**. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO + +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + +**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 the target application. | +| newGroup | GroupType | Yes | Application group. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```javascript +this.bundleName = "com.example.deviceUsageStatistics"; +this.newGroup = stats.GroupType.ACTIVE_GROUP_DAILY; + +bundleState.setBundleGroup(this.bundleName, this.newGroup, (err) => { + if(err) { + console.log('BUNDLE_ACTIVE SetBundleGroup callback failed. because: ' + err.code); + } else { + console.log('BUNDLE_ACTIVE SetBundleGroup callback succeeded.'); + } +}); +``` + +## bundleState.registerGroupCallBack9+ + +registerGroupCallBack(callback: Callback\): Promise\ + +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. + +**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO + +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------- | ---- | ----------- | +| callback | Callback\ | Yes | Callback for application group changes.| + +**Return value** + +| Type | Description | +| ------------- | ----------------------- | +| Promise\ | 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); +}; +bundleState.registerGroupCallBack(onBundleGroupChanged).then( () => { + console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise succeeded.'); +}).catch( err => { + console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise failed. because: ' + err.code); +}); +``` + +## bundleState.registerGroupCallBack9+ + +registerGroupCallBack(callback: Callback\, callback: AsyncCallback\): 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. + +**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO + +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------- | ---- | ------------- | +| callback | Callback\ | Yes | Callback for application group changes. | +| callback | AsyncCallback\ | 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); +}; +bundleState.registerGroupCallBack(onBundleGroupChanged, (err)=>{ + if(err) { + console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback failed, because: ' + err.code); + } else { + console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback success.'); + } +}); +``` + +## bundleState.unRegisterGroupCallBack9+ + +unRegisterGroupCallBack(): Promise\ + +Deregisters the callback for application group changes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO + +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters**: none + +**Return value** + +| Type | Description | +| ------------- | ------------------------ | +| Promise\ | Promise used to return the result.| + +**Example** + +```javascript +bundleState.unRegisterGroupCallBack().then( () => { + console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise succeeded.'); +}).catch( err => { + console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise failed. because: ' + err.code); +}); +``` + +## bundleState.unRegisterGroupCallBack9+ + +unRegisterGroupCallBack(callback: AsyncCallback\): void; + +Deregisters the callback for application group changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO + +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------- | ---- | -------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```javascript +bundleState.unRegisterGroupCallBack((err)=>{ + if(err) { + console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback failed, because: ' + err.code); + } else { + console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback success.'); + } +}); +``` + +## bundleState.queryBundleActiveEventStates9+ + +queryBundleActiveEventStates(begin: number, end: number): Promise<Array<BundleActiveEventState>> + +Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO + +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| begin | number | Yes | Start time.| +| end | number | Yes | End time.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------------------------------- | +| Promise<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Promise used to return the result.| + +**Example** + + ```js + bundleState.queryBundleActiveEventStates(0, 20000000000000).then( res => { + console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise success.'); + console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise result ' + JSON.stringify(res)); + }).catch( err=> { + console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise failed, because: ' + err.code); + }); + ``` + +## bundleState.queryBundleActiveEventStates9+ + +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. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO + +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| begin | number | Yes | Start time. | +| end | number | Yes | End time. | +| callback | AsyncCallback<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Yes | Promise used to return the result.| + +**Example** + + ```js + bundleState.queryBundleActiveEventStates(0, 20000000000000, (err, res) => { + if(err) { + console.log('BUNDLE_ACTIVE queryBundleActiveEventStates callback failed, because: ' + err.code); + } else { + console.log('BUNDLE_ACTIVE queryBundleActiveEventStates callback success.'); + console.log('BUNDLE_ACTIVE queryBundleActiveEventStates callback result ' + JSON.stringify(res)); + } + }); + ``` + +## bundleState.queryAppNotificationNumber9+ + +queryAppNotificationNumber(begin: number, end: number): Promise<Array<BundleActiveEventState>> + +Queries the number of notifications from all applications based on the specified start time and end time. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO + +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| begin | number | Yes | Start time.| +| end | number | Yes | End time.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------------------------------- | +| Promise<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Promise used to return the result.| + +**Example** + + ```js + bundleState.queryAppNotificationNumber(0, 20000000000000).then( res => { + console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise success.'); + console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise result ' + JSON.stringify(res)); + }).catch( err=> { + console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise failed, because: ' + err.code); + }); + ``` + +## bundleState.queryAppNotificationNumber9+ + +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. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO + +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| begin | number | Yes | Start time. | +| end | number | Yes | End time. | +| callback | AsyncCallback<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Yes | Callback used to return the result.| + +**Example** + + ```js + bundleState.queryAppNotificationNumber(0, 20000000000000, (err, res) => { + if(err) { + console.log('BUNDLE_ACTIVE queryAppNotificationNumberCallBack callback failed, because: ' + err.code); + } else { + console.log('BUNDLE_ACTIVE queryAppNotificationNumberCallBack callback success.'); + console.log('BUNDLE_ACTIVE queryAppNotificationNumberCallBack callback result ' + JSON.stringify(res)); + } + }); + ``` + ## BundleActiveModuleInfo9+ Provides the information about the FA usage. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceId | string | No| ID of the device to which the FA belongs.| -| bundleName | string | Yes| Name of the application bundle to which the FA belongs.| -| moduleName | string | Yes| Name of the module to which the FA belongs.| -| abilityName | string | No| **MainAbility** name of the FA.| -| appLabelId | number | No| Application label ID of the FA.| -| labelId | number | No| Label ID of the module to which the FA belongs.| -| descriptionId | number | No| Description ID of the application to which the FA belongs.| -| abilityLableId | number | No| **MainAbility** label ID of the FA.| -| abilityDescriptionId | number | No| **MainAbility** description ID of the FA.| -| abilityIconId | number | No| **MainAbility** icon ID of the FA.| -| launchedCount | number | Yes| Number of FA startup times.| -| lastModuleUsedTime | number | Yes| Last time when the FA is used.| -| formRecords | Array<[BundleActiveFormInfo](#bundleactiveforminfo9)> | Yes| Array of widget usage records in the FA.| +| Name | Type | Mandatory | Description | +| -------------------- | ---------------------------------------- | ---- | ----------------------------- | +| deviceId | string | No | ID of the device to which the FA belongs. | +| bundleName | string | Yes | Name of the application bundle to which the FA belongs. | +| moduleName | string | Yes | Name of the module to which the FA belongs. | +| abilityName | string | No | **MainAbility** name of the FA. | +| appLabelId | number | No | Application label ID of the FA. | +| labelId | number | No | Label ID of the module to which the FA belongs. | +| descriptionId | number | No | Description ID of the application to which the FA belongs. | +| abilityLableId | number | No | **MainAbility** label ID of the FA. | +| abilityDescriptionId | number | No | **MainAbility** description ID of the FA.| +| abilityIconId | number | No | **MainAbility** icon ID of the FA. | +| launchedCount | number | Yes | Number of FA startup times. | +| lastModuleUsedTime | number | Yes | Last time when the FA was used. | +| formRecords | Array<[BundleActiveFormInfo](#bundleactiveforminfo9)> | Yes | Array of widget usage records in the FA. | ## BundleActiveFormInfo9+ Provides the FA widget usage information. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| formName | number | Yes| Widget name.| -| formDimension | number | Yes| Widget dimensions.| -| formId | number | Yes| Widget ID.| -| formLastUsedTime | number | Yes| Last time when the widget was clicked.| -| count | number | Yes| Number of clicks on the widget.| +| Name | Type | Mandatory | Description | +| ---------------- | ------ | ---- | ----------- | +| formName | number | Yes | Widget name. | +| formDimension | number | Yes | Widget dimensions. | +| formId | number | Yes | Widget ID. | +| formLastUsedTime | number | Yes | Last time when the widget was clicked.| +| count | number | Yes | Number of clicks on the widget. | + +## BundleActiveGroupCallbackInfo9+ + +Provides the application group changes returned through a callback. + +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App + +| 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. | ## BundleStateInfo -Provides the usage duration information of an application. + +Provides the usage duration information of applications. ### Attributes -**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Application bundle name.| -| 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.| -| abilityPrevSeenTime | number | No| Last time when the application was visible in the foreground.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| -| abilitySeenTotalTime | number | No| Total time when the application is visible in the foreground.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| -| fgAbilityAccessTotalTime | number | No| Total time that the application accesses the foreground.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| -| fgAbilityPrevAccessTime | number | No| Last time when the application accessed the foreground.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| -| infosBeginTime | number | No| Time logged in the first application usage record in the **BundleActiveInfo** object.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| -| infosEndTime | number | No| Time logged in the last application usage record in the **BundleActiveInfo** object.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| Name | Type | Mandatory | Description | +| ------------------------ | ------ | ---- | ---------------------------------------- | +| bundleName | string | Yes | Bundle name of the application. | +| abilityPrevAccessTime | number | Yes | Last time when the application was used. | +| abilityInFgTotalTime | number | Yes | Total time that the application runs in the foreground. | +| id | number | No | User ID.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| abilityPrevSeenTime | number | No | Last time when the application was visible in the foreground.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| abilitySeenTotalTime | number | No | Total time that the application is visible in the foreground.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| fgAbilityAccessTotalTime | number | No | Total time that the application accesses the foreground.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| fgAbilityPrevAccessTime | number | No | Last time when the application accessed the foreground.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| infosBeginTime | number | No | Time logged in the first application usage record in the **BundleActiveInfo** object.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| infosEndTime | number | No | Time logged in the last application usage record in the **BundleActiveInfo** object.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| ### merge @@ -562,9 +1035,9 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. It will be a **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| toMerge | [BundleStateInfo](#bundlestateinfo) | Yes| Application usage information to merge.| +| Name | Type | Mandatory | Description | +| ------- | ----------------------------------- | ---- | -------------- | +| toMerge | [BundleStateInfo](#bundlestateinfo) | Yes | Application usage information to merge.| ## BundleActiveState @@ -572,14 +1045,14 @@ Provides information about an application event. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Application bundle name.| -| 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.| -| indexOfLink | string | No| Shortcut ID.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| -| nameOfClass | string | No| Class name.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| Name | Type | Mandatory | Description | +| --------------------- | ------ | ---- | ---------------------------------------- | +| bundleName | string | Yes | Bundle name of the 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.| +| indexOfLink | string | No | Shortcut ID.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| nameOfClass | string | No | Class name.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| ## BundleActiveInfoResponse @@ -587,9 +1060,23 @@ Provides the usage duration information of applications. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| [key: string]: BundleStateInfo | [key: string]: [BundleStateInfo](#bundlestateinfo) | Yes| Usage duration information by application.| +| Name | Type | Mandatory | Description | +| ------------------------------ | ---------------------------------------- | ---- | -------------- | +| [key: string]: BundleStateInfo | [key: string]: [BundleStateInfo](#bundlestateinfo) | Yes | Usage duration information by application.| + +## BundleActiveEventState9+ + +Provides statistics about notifications and system events. + +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----------------- | +| name | string | Yes | Bundle name of the notification sending application or system event name. | +| eventId | number | Yes | Type of the notification or system event. | +| count | number | Yes | Number of application notifications or system event triggering times.| ## IntervalType @@ -597,10 +1084,25 @@ Enumerates the interval types for querying the application usage duration. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App -|Name |Default Value |Description| -| -------- | -------- | -------- | -| BY_OPTIMIZED | 0 | The system obtains the application usage duration statistics in the specified time frame at the interval the system deems appropriate.| -| BY_DAILY | 1 | The system obtains the application usage duration statistics in the specified time frame on a daily basis.| -| BY_WEEKLY | 2 | The system obtains the application usage duration statistics in the specified time frame on a weekly basis.| -| 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.| +| Name | Default Value | Description | +| ------------ | ---- | ---------------------------------------- | +| BY_OPTIMIZED | 0 | The system obtains the application usage duration statistics in the specified time frame at the interval the system deems appropriate.| +| BY_DAILY | 1 | The system obtains the application usage duration statistics in the specified time frame on a daily basis. | +| BY_WEEKLY | 2 | The system obtains the application usage duration statistics in the specified time frame on a weekly basis. | +| 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 + +Enumerates the application group types. + +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + +| Name | Default Value | Description | +| ------------------ | ---- | ----------------- | +| ACTIVE_GROUP_ALIVE | 10 | Group of active applications. | +| ACTIVE_GROUP_DAILY | 20 | Group of frequently used applications that are not in the active state. | +| ACTIVE_GROUP_FIXED | 30 | Group of applications that are used periodically but not every day.| +| ACTIVE_GROUP_RARE | 40 | Group of rarely used applications. | +| ACTIVE_GROUP_LIMIT | 50 | Group of restricted applications. | +| ACTIVE_GROUP_NEVER | 60 | Group of applications that have been installed but never run. | diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index 22ea52f17d7b5996d536c8dc223ada7ee9ae1fa2..994fe3a673ca9d505c0a6f96df6f007fe6d027d4 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -168,11 +168,10 @@ Enables listening. **Example** ```js - var type = "add"; var callback = (data) => { console.info('Listening enabled. Data: ' + JSON.stringify(data)) } - display.on(type, callback); + display.on("add", callback); ``` @@ -192,6 +191,5 @@ Disables listening. **Example** ```js - var type = "remove"; - display.off(type); + display.off("remove"); ``` 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 6bbe4a0111f7fa6d409457e705af60cf6d0376c7..2fdd9e1b06f1bfd40c30e941068e821a916204ae 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -3,6 +3,7 @@ Distributed data management provides collaboration between databases of different devices for applications. The APIs provided by distributed data management can be used to save data to the distributed database and perform operations such as adding, deleting, modifying, and querying data in the distributed database. >**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. @@ -610,14 +611,14 @@ Defines the KV store constants. | --- | ---- | ----------------------- | | MAX_KEY_LENGTH | 1024 | Maximum length (in bytes) of a key in the KV store. | | MAX_VALUE_LENGTH | 4194303 | Maximum length (in bytes) of a value in the KV store. | -| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of the device coordinate key. | +| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of the device key, in bytes.| | MAX_STORE_ID_LENGTH | 128 | Maximum length (in bytes) of a KV store ID. | -| MAX_QUERY_LENGTH | 512000 | Maximum query length. | -| MAX_BATCH_SIZE | 128 | Maximum size of a batch operation. | +| MAX_QUERY_LENGTH | 512000 | Maximum query length, in bytes.| +| MAX_BATCH_SIZE | 128 | Maximum number of batch operations.| ## Schema8+ ## -Defines a database schema. When creating or opening a KV store, you can create a **Schema** object and put it into **Options**. +Defines the schema of a KV store. When creating or opening a KV store, you can create a **Schema** object and put it in [Options](#options). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -731,15 +732,15 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + err); + console.log('getResultSet failed:' + err); }); const count = resultSet.getCount(); - console.log("GetCount " + count); + console.log("getCount succeed:" + count); } catch (e) { - console.log("GetCount fail " + e); + console.log("getCount failed: " + e); } ``` @@ -764,15 +765,15 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); + console.log('getResultSet succeeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + err); + console.log('getResultSet failed:' + err); }); const position = resultSet.getPosition(); - console.log("getPosition " + position); + console.log("getPosition succeed:" + position); } catch (e) { - console.log("GetPosition fail " + e); + console.log("getPosition failed: " + e); } ``` @@ -798,15 +799,15 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + err); + console.log('getResultSet failed: ' + err); }); - const moved = resultSet.moveToFirst(); - console.log("moveToFirst " + moved); + const moved1 = resultSet.moveToFirst(); + console.log("moveToFirst succeed: " + moved1); } catch (e) { - console.log("MoveToFirst fail " + e); + console.log("moveToFirst failed " + e); } ``` @@ -832,15 +833,15 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + err); + console.log('getResultSet failed: ' + err); }); - const moved = resultSet.moveToLast(); - console.log("moveToLast " + moved); + const moved2 = resultSet.moveToLast(); + console.log("moveToLast succeed:" + moved2); } catch (e) { - console.log("moveToLast fail " + e); + console.log("moveToLast failed: " + e); } ``` @@ -866,15 +867,15 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + err); + console.log('getResultSet failed: ' + err); }); - const moved = resultSet.moveToNext(); - console.log("moveToNext " + moved); + const moved3 = resultSet.moveToNext(); + console.log("moveToNext succeed: " + moved3); } catch (e) { - console.log("moveToNext fail " + e); + console.log("moveToNext failed: " + e); } ``` @@ -900,15 +901,15 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + err); + console.log('getResultSet failed: ' + err); }); - const moved = resultSet.moveToPrevious(); - console.log("moveToPrevious " + moved); + const moved4 = resultSet.moveToPrevious(); + console.log("moveToPrevious succeed:" + moved4); } catch (e) { - console.log("moveToPrevious fail " + e); + console.log("moveToPrevious failed: " + e); } ``` @@ -940,15 +941,15 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + err); + console.log('getResultSet failed: ' + err); }); - const moved = resultSet.move(); - console.log("move " + moved); + const moved5 = resultSet.move(); + console.log("move succeed:" + moved5); } catch (e) { - console.log("move fail " + e); + console.log("move failed: " + e); } ``` @@ -980,15 +981,15 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + err); + console.log('getResultSet failed: ' + err); }); - const moved = resultSet.moveToPosition(); - console.log("moveToPosition " + moved); + const moved6 = resultSet.moveToPosition(); + console.log("moveToPosition succeed: " + moved6); } catch (e) { - console.log("moveToPosition fail " + e); + console.log("moveToPosition failed: " + e); } ``` @@ -1014,15 +1015,15 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + err); + console.log('getResultSet failed: ' + err); }); - const moved = resultSet.isFirst(); - console.log("isFirst " + moved); + const isfirst = resultSet.isFirst(); + console.log("Check isFirst succeed:" + isfirst); } catch (e) { - console.log("isFirst fail " + e); + console.log("Check isFirst failed: " + e); } ``` @@ -1048,15 +1049,15 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + err); + console.log('getResultSet failed: ' + err); }); - const moved = resultSet.isLast(); - console.log("isLast " + moved); + const islast = resultSet.isLast(); + console.log("Check isLast succeed: " + islast); } catch (e) { - console.log("isLast fail " + e); + console.log("Check isLast failed: " + e); } ``` @@ -1081,15 +1082,15 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + err); + console.log('getResultSet failed: ' + err); }); - const moved = resultSet.isBeforeFirst(); - console.log("isBeforeFirst " + moved); + const isbeforefirst = resultSet.isBeforeFirst(); + console.log("Check isBeforeFirst succeed: " + isbeforefirst); } catch (e) { - console.log("isBeforeFirst fail " + e); + console.log("Check isBeforeFirst failed: " + e); } ``` @@ -1115,15 +1116,15 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + err); + console.log('getResultSet failed: ' + err); }); - const moved = resultSet.isAfterLast(); - console.log("isAfterLast " + moved); + const isafterlast = resultSet.isAfterLast(); + console.log("Check isAfterLast succeed:" + isafterlast); } catch (e) { - console.log("isAfterLast fail " + e); + console.log("Check isAfterLast failed: " + e); } ``` @@ -1149,16 +1150,15 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + err); + console.log('getResultSet failed: ' + err); }); - const moved = resultSet.moveToNext(); const entry = resultSet.getEntry(); - console.log("getEntry " + JSON.stringify(entry)); + console.log("getEntry succeed:" + JSON.stringify(entry)); } catch (e) { - console.log("getEntry fail " + e); + console.log("getEntry failed: " + e); } ``` @@ -1221,7 +1221,7 @@ Creates a **Query** object to match the specified field whose value is equal to | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | | value | number\|string\|boolean | Yes | Value specified.| **Return value** @@ -1239,7 +1239,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1256,7 +1256,7 @@ Creates a **Query** object to match the specified field whose value is not equal | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | | value | number\|string\|boolean | Yes | Value specified.| **Return value** @@ -1274,7 +1274,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1291,7 +1291,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | | value | number\|string\|boolean | Yes | Value specified.| **Return value** @@ -1309,7 +1309,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1326,7 +1326,7 @@ Creates a **Query** object to match the specified field whose value is less than | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | | value | number\|string\|boolean | Yes | Value specified.| **Return value** @@ -1344,7 +1344,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1361,7 +1361,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | | value | number\|string\|boolean | Yes | Value specified.| **Return value** @@ -1379,7 +1379,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1396,7 +1396,7 @@ Creates a **Query** object to match the specified field whose value is less than | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | | value | number\|string\|boolean | Yes | Value specified.| **Return value** @@ -1414,7 +1414,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1432,7 +1432,7 @@ Creates a **Query** object to match the specified field whose value is **null**. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | **Return value** @@ -1449,7 +1449,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1467,7 +1467,7 @@ Creates a **Query** object to match the specified field whose value is within th | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | | valueList | number[] | Yes | List of numbers.| **Return value** @@ -1485,7 +1485,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1502,7 +1502,7 @@ Creates a **Query** object to match the specified field whose value is within th | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | | valueList | string[] | Yes | List of strings.| **Return value** @@ -1520,7 +1520,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1537,7 +1537,7 @@ Creates a **Query** object to match the specified field whose value is not withi | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | | valueList | number[] | Yes | List of numbers.| **Return value** @@ -1555,7 +1555,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1572,7 +1572,7 @@ Creates a **Query** object to match the specified field whose value is not withi | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | | valueList | string[] | Yes | List of strings.| **Return value** @@ -1590,7 +1590,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1607,8 +1607,8 @@ Creates a **Query** object to match the specified field whose value is similar t | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | -| valueList | string | Yes | String specified.| +| fieId | string | Yes Field to match. It cannot contain '^'. | +| value | string | Yes | String specified.| **Return value** @@ -1625,7 +1625,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1642,8 +1642,8 @@ Creates a **Query** object to match the specified field whose value is not simil | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | -| valueList | string | Yes | String specified.| +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | string | Yes | String specified.| **Return value** @@ -1660,7 +1660,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1690,7 +1690,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1720,7 +1720,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1737,7 +1737,7 @@ Creates a **Query** object to sort the query results in ascending order. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | **Return value** @@ -1755,7 +1755,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1772,7 +1772,7 @@ Creates a **Query** object to sort the query results in descending order. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | **Return value** @@ -1790,7 +1790,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1826,7 +1826,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1860,7 +1860,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1890,7 +1890,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1920,7 +1920,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1955,7 +1955,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1990,7 +1990,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -2041,7 +2041,7 @@ Obtains the query statement of this **Query** object. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| string |Query statement obtained.| **Example** @@ -2051,16 +2051,14 @@ try { let sql1 = query.getSqlLike(); console.log("GetSqlLike sql=" + sql1); } catch (e) { - console.log("dumplicated calls should be ok : " + e); + console.log("duplicated calls should be ok : " + e); } ``` ## KVStore -Provides methods to manage data in a KV store, for example, adding or deleting data and subscribing to data changes or completion of data synchronization. Before calling any method in **KVStore**, you must use **getKVStore** to obtain a **KVStore** object. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core +Provides methods to manage data in a KV store, for example, adding or deleting data and subscribing to data changes or completion of data synchronization. Before calling any method in **KVStore**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. ### put @@ -2927,8 +2925,6 @@ These value types can be used only by internal applications. Provides methods to query and synchronize data in a single KV store. This class inherits from **KVStore**. Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** object. -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - ### get get(key: string, callback: AsyncCallback<Uint8Array | string | boolean | number>): void @@ -3222,7 +3218,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ ### getResultSet(keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void @@ -3258,7 +3254,7 @@ try { kvStore.putBatch(entries, async function (err, data) { console.log('GetResultSet putBatch success'); await kvStore.getResultSet('batch_test_string_key', async function (err, result) { - console.log('GetResultSet getResultSet success'); + console.log('GetResultSet getResultSet succeed.'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { console.log('GetResultSet closeResultSet success'); @@ -3315,10 +3311,10 @@ try { console.log('PutBatch putBatch fail ' + JSON.stringify(err)); }); kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('GetResult getResultSet success'); + console.log('GetResult getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); + console.log('getResultSet failed: ' + JSON.stringify(err)); }); kvStore.closeResultSet(resultSet).then((err) => { console.log('GetResult closeResultSet success'); @@ -3369,7 +3365,7 @@ try { const query = new distributedData.Query(); query.prefixKey("batch_test"); await kvStore.getResultSet(query, async function (err, result) { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; }); }); @@ -3425,10 +3421,10 @@ try { const query = new distributedData.Query(); query.prefixKey("batch_test"); kvStore.getResultSet(query).then((result) => { - console.log(' getResultSet success'); + console.log(' getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); + console.log('getResultSet failed: ' + JSON.stringify(err)); }); }catch(e) { console.log('GetResultSet e ' + e); @@ -3439,7 +3435,7 @@ try { closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void -Closes the **KvStoreResultSet** object obtained by **getResultSet**. This API uses an asynchronous callback to return the result. +Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3473,7 +3469,7 @@ try { closeResultSet(resultSet: KvStoreResultSet): Promise<void> -Closes the **KvStoreResultSet** object obtained by **getResultSet**. This API uses a promise to return the result. +Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3543,7 +3539,7 @@ try { const query = new distributedData.Query(); query.prefixKey("batch_test"); await kvStore.getResultSize(query, async function (err, resultSize) { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); }); }); } catch(e) { @@ -3597,9 +3593,9 @@ try { const query = new distributedData.Query(); query.prefixKey("batch_test"); kvStore.getResultSize(query).then((resultSize) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); + console.log('getResultSet failed: ' + JSON.stringify(err)); }); }catch(e) { console.log('GetResultSize e ' + e); @@ -3769,7 +3765,7 @@ try { sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void -Manually triggers KV store synchronization synchronously. +Manually triggers KV store synchronization synchronously. For details about the synchronization mode of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -3794,7 +3790,7 @@ kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000); setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void -Sets the default delay of database synchronization. This API uses an asynchronous callback to return the result. +Sets the default delay allowed for KV store synchronization. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3824,7 +3820,7 @@ try { setSyncParam(defaultAllowedDelayMs: number): Promise<void> -Sets the default delay of database synchronization. This API uses a promise to return the result. +Sets the default delay allowed for KV store synchronization. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3898,7 +3894,7 @@ Obtains the security level of this KV store. This API uses a promise to return t | Type | Description | | ------ | ------- | -|Promise<[SecurityLevel](#securitylevel)> |Promise used to return the security level obtained.| +|Promise<[SecurityLevel](#securitylevel)> |Promise used to return the value obtained.| **Example** @@ -3920,8 +3916,6 @@ try { Provides methods to manage distributed data by device in the distributed system. This class inherits from **KVStore** and provides data query and synchronization methods. Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object. -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - ### get8+ ### get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|number|Uint8Array>): void @@ -4333,7 +4327,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ ### getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void @@ -4356,7 +4350,7 @@ let kvStore; try { let resultSet; kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; await kvStore.closeResultSet(resultSet, function (err, data) { console.log('closeResultSet success'); @@ -4396,10 +4390,10 @@ let kvStore; try { let resultSet; kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); + console.log('getResultSet failed: ' + JSON.stringify(err)); }); kvStore.closeResultSet(resultSet).then((err) => { console.log('closeResultSet success'); @@ -4451,7 +4445,7 @@ try { query.prefixKey("batch_test"); query.deviceId('localDeviceId'); await kvStore.getResultSet(query, async function (err, result) { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; await kvStore.closeResultSet(resultSet, function (err, data) { console.log('closeResultSet success'); @@ -4512,10 +4506,10 @@ try { query.prefixKey("batch_test"); console.log("GetResultSet " + query.getSqlLike()); kvStore.getResultSet(query).then((result) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); + console.log('getResultSet failed: ' + JSON.stringify(err)); }); kvStore.closeResultSet(resultSet).then((err) => { console.log('closeResultSet success'); @@ -4567,7 +4561,7 @@ try { const query = new distributedData.Query(); query.prefixKey("batch_test"); await kvStore.getResultSet('localDeviceId', query, async function (err, result) { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); resultSet = result; await kvStore.closeResultSet(resultSet, function (err, data) { console.log('closeResultSet success'); @@ -4627,10 +4621,10 @@ try { const query = new distributedData.Query(); query.prefixKey("batch_test"); kvStore.getResultSet('localDeviceId', query).then((result) => { - console.log('GetResultSet getResultSet success'); + console.log('GetResultSet getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('GetResultSet getResultSet fail ' + JSON.stringify(err)); + console.log('GetResultSet getResultSet failed: ' + JSON.stringify(err)); }); query.deviceId('localDeviceId'); console.log("GetResultSet " + query.getSqlLike()); @@ -4650,7 +4644,7 @@ try { closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void -Closes the **KvStoreResultSet** object obtained by **getResultSet**. This API uses an asynchronous callback to return the result. +Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4685,7 +4679,7 @@ try { closeResultSet(resultSet: KvStoreResultSet): Promise<void> -Closes the **KvStoreResultSet** object obtained by **getResultSet**. This API uses a promise to return the result. +Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4757,7 +4751,7 @@ try { query.prefixKey("batch_test"); query.deviceId('localDeviceId'); await kvStore.getResultSize(query, async function (err, resultSize) { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); }); }); } catch(e) { @@ -4812,9 +4806,9 @@ try { query.prefixKey("batch_test"); query.deviceId('localDeviceId'); kvStore.getResultSize(query).then((resultSize) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); + console.log('getResultSet failed: ' + JSON.stringify(err)); }); }catch(e) { console.log('GetResultSize e ' + e); @@ -4860,7 +4854,7 @@ try { const query = new distributedData.Query(); query.prefixKey("batch_test"); await kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); }); }); } catch(e) { @@ -4915,9 +4909,9 @@ try { var query = new distributedData.Query(); query.prefixKey("batch_test"); kvStore.getResultSize('localDeviceId', query).then((resultSize) => { - console.log('getResultSet success'); + console.log('getResultSet succeed.'); }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); + console.log('getResultSet failed: ' + JSON.stringify(err)); }); }catch(e) { console.log('GetResultSize e ' + e); @@ -5020,7 +5014,7 @@ try { sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void -Manually triggers KV store synchronization synchronously. +Manually triggers KV store synchronization synchronously. For details about the synchronization mode of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -5031,7 +5025,7 @@ Manually triggers KV store synchronization synchronously. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceIdList |string[] | Yes |IDs of the devices to be synchronized.| -| mode |[SyncMode](#syncmode) | Yes |Data synchronization mode, which can be **PUSH**, **PULL**, or **PUSH_PULL**. | +| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | | allowedDelayMs |number | No |Allowed synchronization delay time, in ms. | **Example** @@ -5123,7 +5117,7 @@ try { ## SyncMode -Defines the synchronization mode. +Enumerates the synchronization modes. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core diff --git a/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md b/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md index 869472d43c046a68cd3d50cfe262b424b660dd0d..25c0dbf964cc82eaddc85ff1114c440afbd00d2d 100644 --- a/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md @@ -11,11 +11,11 @@ import enterpriseDeviceManager from '@ohos.enterpriseDeviceManager'; ``` -## enterpriseDeviceManager.activateAdmin +## enterpriseDeviceManager.enableAdmin -activateAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, callback: AsyncCallback\): void +enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId?: number, callback: AsyncCallback\): void -Activates a device administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. +Enables a device administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -27,12 +27,13 @@ SystemCapability.Customation.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | - | enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | - | type | [AdminType](#AdminType) | Yes | Type of the device administrator to activate. | - | callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | +| 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. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -45,7 +46,7 @@ let enterpriseInfo = { name: "enterprise name", description: "enterprise description" } -enterpriseDeviceManager.activateAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, (error, result) => { +enterpriseDeviceManager.enableAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, 100, (error, result) => { if (error != null) { console.log("error occurs" + error); return; @@ -54,11 +55,11 @@ enterpriseDeviceManager.activateAdmin(wantTemp, enterpriseInfo, enterpriseDevice }); ``` -## enterpriseDeviceManager.activateAdmin +## enterpriseDeviceManager.enableAdmin -activateAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType): Promise\ +enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId?: number): Promise\ -Activates a device administrator application based on the specified bundle name and class name. This API uses a promise to return the result. +Enables a device administrator application based on the specified bundle name and class name. This API uses a promise to return the result. **Required permissions** @@ -70,11 +71,12 @@ SystemCapability.Customation.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------------- | ---------------------------------------------- | ---- | ------------------------ | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | - | enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | - | type | [AdminType](#AdminType) | Yes | Type of the device administrator to activate. | +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------------- | ---- | ------------------------ | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | +| 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. | **Return value** @@ -93,7 +95,7 @@ let enterpriseInfo = { name: "enterprise name", description: "enterprise description" } -enterpriseDeviceManager.activateAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL) +enterpriseDeviceManager.enableAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, 100) .then((result) => { console.log(result); }).catch(error => { @@ -101,11 +103,11 @@ enterpriseDeviceManager.activateAdmin(wantTemp, enterpriseInfo, enterpriseDevice }); ``` -## enterpriseDeviceManager.deactivateAdmin +## enterpriseDeviceManager.disableAdmin -deactivateAdmin(admin: Want, callback: AsyncCallback\): void +disableAdmin(admin: Want, userId?: number, callback: AsyncCallback\): void -Deactivates a device common administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. +Disables a device common administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -117,10 +119,11 @@ SystemCapability.Customation.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ---------------------------------------------- | ---- | ------------------------------ | - | admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | - | callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------------- | ---- | ------------------------------ | +| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | +| 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. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -129,7 +132,7 @@ let wantTemp = { bundleName: elementName.bundleName, abilityName: elementName.abilityName, }; -enterpriseDeviceManager.deactivateAdmin(wantTemp, (error, result) => { +enterpriseDeviceManager.disableAdmin(wantTemp, 100, (error, result) => { if (error != null) { console.log("error occurs" + error); return; @@ -140,11 +143,11 @@ enterpriseDeviceManager.deactivateAdmin(wantTemp, (error, result) => { -## enterpriseDeviceManager.deactivateAdmin +## enterpriseDeviceManager.disableAdmin -deactivateAdmin(admin: Want): Promise\ +disableAdmin(admin: Want, userId?: number): Promise\ -Deactivates a device common administrator application based on the specified bundle name and class name. This API uses a promise to return the result. +Disables a device common administrator application based on the specified bundle name and class name. This API uses a promise to return the result. **Required permissions** @@ -156,9 +159,10 @@ SystemCapability.Customation.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ------ | ---------------------------------------------- | ---- | ------------------ | - | admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | +| Name | Type | Mandatory | Description | +| ------ | ---------------------------------------------- | ---- | ------------------ | +| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | +| 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. | **Return value** @@ -173,18 +177,18 @@ let wantTemp = { bundleName: "bundleName", abilityName: "abilityName", }; -enterpriseDeviceManager.deactivateAdmin(wantTemp).then((result) => { +enterpriseDeviceManager.disableAdmin(wantTemp, 100).then((result) => { console.log(result); }).catch(error => { console.log("error occurs" + error); }); ``` -## enterpriseDeviceManager.deactivateSuperAdmin +## enterpriseDeviceManager.disableSuperAdmin -deactivateSuperAdmin(bundleName: String, callback: AsyncCallback\): void +disableSuperAdmin(bundleName: String, callback: AsyncCallback\): void -Deactivates a device super administrator application based on the specified bundle name. This API uses an asynchronous callback to return the result. +Disables a device super administrator application based on the specified bundle name. This API uses an asynchronous callback to return the result. **System capability** @@ -201,7 +205,7 @@ SystemCapability.Customation.EnterpriseDeviceManager ``` let bundleName = "com.example.myapplication"; -enterpriseDeviceManager.deactivateSuperAdmin(bundleName, (error, result) => { +enterpriseDeviceManager.disableSuperAdmin(bundleName, (error, result) => { if (error != null) { console.log("error occurs" + error); return; @@ -210,11 +214,11 @@ enterpriseDeviceManager.deactivateSuperAdmin(bundleName, (error, result) => { }); ``` -## enterpriseDeviceManager.deactivateSuperAdmin +## enterpriseDeviceManager.disableSuperAdmin -deactivateSuperAdmin(bundleName: String): Promise\ +disableSuperAdmin(bundleName: String): Promise\ -Deactivates a device super administrator application based on the specified bundle name. This API uses a promise to return the result. +Disables a device super administrator application based on the specified bundle name. This API uses a promise to return the result. **System capability** @@ -236,18 +240,18 @@ SystemCapability.Customation.EnterpriseDeviceManager ``` let bundleName = "com.example.myapplication"; -enterpriseDeviceManager.deactivateSuperAdmin(bundleName).then((result) => { +enterpriseDeviceManager.disableSuperAdmin(bundleName).then((result) => { console.log(result); }).catch(error => { console.log("error occurs" + error); }); ``` -## enterpriseDeviceManager.isAdminAppActive +## enterpriseDeviceManager.isAdminEnabled -isAdminAppActive(admin: Want, callback: AsyncCallback\): void +isAdminEnabled(admin: Want, userId?: number, callback: AsyncCallback\): void -Checks whether a device administrator application is activated based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. +Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. **System capability** @@ -255,10 +259,11 @@ SystemCapability.Customation.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ---------------------------------------------- | ---- | -------------------------------- | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | - | callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------------- | ---- | -------------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| 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. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -267,7 +272,7 @@ let wantTemp = { bundleName: elementName.bundleName, abilityName: elementName.abilityName, }; -enterpriseDeviceManager.isAdminAppActive(wantTemp, (error, result) => { +enterpriseDeviceManager.isAdminEnabled(wantTemp, 100, (error, result) => { if (error != null) { console.log("error occurs" + error); return; @@ -278,11 +283,11 @@ enterpriseDeviceManager.isAdminAppActive(wantTemp, (error, result) => { -## enterpriseDeviceManager.isAdminAppActive +## enterpriseDeviceManager.isAdminEnabled -isAdminAppActive(admin: Want): Promise\ +isAdminEnabled(admin: Want, userId?: number): Promise\ -Checks whether a device administrator application is activated based on the specified bundle name and class name. This API uses a promise to return the result. +Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses a promise to return the result. **System capability** @@ -290,9 +295,10 @@ SystemCapability.Customation.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ------ | ---------------------------------------------- | ---- | -------------- | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| Name | Type | Mandatory | Description | +| ------ | ---------------------------------------------- | ---- | -------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| 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. | **Return value** @@ -307,7 +313,7 @@ let wantTemp = { bundleName: "bundleName", abilityName: "abilityName", }; -enterpriseDeviceManager.isAdminAppActive(wantTemp).then((result) => { +enterpriseDeviceManager.isAdminEnabled(wantTemp, 100).then((result) => { console.log(result); }).catch(error => { console.log("error occurs" + error); @@ -318,7 +324,7 @@ enterpriseDeviceManager.isAdminAppActive(wantTemp).then((result) => { isSuperAdmin(bundleName: String, callback: AsyncCallback\): void -Checks whether a device super administrator application is activated based on the specified bundle name. This API uses an asynchronous callback to return the result. +Checks whether a device super administrator application is enabled based on the specified bundle name. This API uses an asynchronous callback to return the result. **System capability** @@ -350,7 +356,7 @@ enterpriseDeviceManager.isSuperAdmin(bundleName, (error, result) => { isSuperAdmin(bundleName: String): Promise\ -Checks whether a device super administrator application is activated based on the specified bundle name. This API uses a promise to return the result. +Checks whether a device super administrator application is enabled based on the specified bundle name. This API uses a promise to return the result. **System capability** diff --git a/en/application-dev/reference/apis/js-apis-eventhub.md b/en/application-dev/reference/apis/js-apis-eventhub.md index f2d605b94821c591812c73bbb10defa04a6a40e1..a5a25efdbab5c977e92b85a5fcc656f5c3ae3ef7 100644 --- a/en/application-dev/reference/apis/js-apis-eventhub.md +++ b/en/application-dev/reference/apis/js-apis-eventhub.md @@ -1,8 +1,9 @@ # EventHub -> **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. - +> **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 APIs of this module can be used only in the stage model. Implements event subscription, unsubscription, and triggering. @@ -14,11 +15,8 @@ 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. - - ```js import Ability from '@ohos.application.Ability' export default class MainAbility extends Ability { 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 630dc3f6a7c8b785bf8c1b8d950250f8f194fa1c..afd1cec9cd5df1eaaedfc8679e1dc478e8e09766 100644 --- a/en/application-dev/reference/apis/js-apis-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-extension-context.md @@ -3,19 +3,18 @@ > **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. -```js -import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbility'; -``` - - 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.| diff --git a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md b/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md index 05a2fb5bdfda8d4f86e0283b7d9abdeeee2e2f22..62f6d9b631aa687e61fc6a1b4fe26fb72f16f105 100644 --- a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md @@ -1,9 +1,9 @@ # ExtensionRunningInfo -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - Provides extension running information. ## Modules to Import @@ -14,11 +14,8 @@ import abilitymanager from '@ohos.application.abilityManager'; ## Usage - The extension running information is obtained through an **abilityManager** instance. - - ```js import abilitymanager from '@ohos.application.abilityManager'; let upperLimit=1 diff --git a/en/application-dev/reference/apis/js-apis-faultLogger.md b/en/application-dev/reference/apis/js-apis-faultLogger.md index 3ce1c4b5c66f8d1ce7d33f3a6edb036bab72d4ea..9cfb16523cf8c3333f8193d803be03c61e45a139 100644 --- a/en/application-dev/reference/apis/js-apis-faultLogger.md +++ b/en/application-dev/reference/apis/js-apis-faultLogger.md @@ -52,8 +52,7 @@ Obtains the fault information about the current process. This API uses an asynch | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | faultType | [FaultType](#faulttype) | Yes| Fault type.| -| callback | AsyncCallbackArray<Array<[FaultLogInfo](#faultloginfo)>> | Yes| Callback used to return the fault information array.
The value is the fault information array obtained. If the value is **undefined**, an exception occurs during the information retrieval. In this case, an error string will be returned. - +| callback | AsyncCallbackArray<Array<[FaultLogInfo](#faultloginfo)>> | Yes | Callback used to return the fault information array.
The value is the fault information array obtained. If the value is **undefined**, an exception occurs during the information retrieval. In this case, an error string will be returned. | **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-featureAbility.md b/en/application-dev/reference/apis/js-apis-featureAbility.md index b57f529219338640cc0494bd24611063bcc4661d..4c15fefc458a174ee0477d23b77aa9796f2bb051 100644 --- a/en/application-dev/reference/apis/js-apis-featureAbility.md +++ b/en/application-dev/reference/apis/js-apis-featureAbility.md @@ -1,7 +1,9 @@ -# FeatureAbility Module (JavaScript) +# FeatureAbility -> ![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. +> **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 APIs of this module can be used only in the FA model. ## Constraints @@ -44,7 +46,7 @@ featureAbility.startAbility( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability name. */ - abilityName: "com.example.entry.secondAbility",, + abilityName: "com.example.entry.secondAbility", uri: "" }, }, @@ -139,7 +141,7 @@ Starts an ability. This API uses a callback to return the execution result when **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant' featureAbility.startAbilityForResult( { @@ -157,7 +159,7 @@ featureAbility.startAbilityForResult( }, }, (err, data) => { - console.info("err: " + JSON.stringfy(err) + "data: " + JSON.stringfy(data)) + console.info("err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)) } ) ``` @@ -185,7 +187,7 @@ Starts an ability. This API uses a promise to return the execution result when t **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant' featureAbility.startAbilityForResult( { @@ -291,7 +293,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant' featureAbility.terminateSelfWithResult( { @@ -343,7 +345,7 @@ Checks whether the main window of this ability has the focus. This API uses a ca **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; featureAbility.hasWindowFocus() ``` @@ -391,7 +393,7 @@ Obtains the **Want** object sent from this ability. This API uses a callback to **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; featureAbility.getWant() ``` @@ -414,7 +416,7 @@ Obtains the **Want** object sent from this ability. This API uses a promise to r **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; featureAbility.getWant().then((data) => { console.info("==========================>getWantCallBack=======================>"); }); @@ -437,7 +439,7 @@ Obtains the application context. **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext() context.getBundleName() ``` @@ -461,7 +463,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; featureAbility.terminateSelf() ``` @@ -484,7 +486,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; featureAbility.terminateSelf().then((data) => { console.info("==========================>terminateSelfCallBack=======================>"); }); @@ -918,13 +920,12 @@ Enumerates operation types of the Data ability. | ------------------- | ---- | -------------------- | ---- | -------------------------------------- | | want | Read-only | [Want](js-apis-application-Want.md) | Yes | Information about the ability to start. | | abilityStartSetting | Read-only | {[key: string]: any} | No | Special attribute of the ability to start. This attribute can be passed in the method call.| - | ## flags **System capability**: SystemCapability.Ability.AbilityBase -| Name | Name | Description | +| 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. | diff --git a/en/application-dev/reference/apis/js-apis-filemanager.md b/en/application-dev/reference/apis/js-apis-filemanager.md index b7e33e70ef01cec6ed41308fbc2f102ef2176c28..5d1e0db973a372a82daa363ed62a38177265b5cf 100644 --- a/en/application-dev/reference/apis/js-apis-filemanager.md +++ b/en/application-dev/reference/apis/js-apis-filemanager.md @@ -1,9 +1,11 @@ # User File Access and Management ->![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. +>- 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. Currently, these APIs can be called only by **filepicker**. +This module provides service APIs for accessing and managing user files. It interworks with the underlying file management services to implement media library and external card management, and provides capabilities for applications to query and create user files. + ## Modules to Import ```js @@ -156,7 +158,7 @@ Obtains information about the second-level album or files in asynchronous mode. ## filemanager.createFile -filemanager.createFile(path : string, filename : string, options? : {dev? : DevInfo}) : Promise<string> +createFile(path : string, filename : string, options? : {dev? : DevInfo}) : Promise<string> Creates a file in the specified path in asynchronous mode. This API uses a promise to return the result. @@ -173,7 +175,7 @@ Creates a file in the specified path in asynchronous mode. This API uses a promi | Type| Description| | --- | -- | - | promise| Promise used to return the URI of the file created.| + | Promise<string> | Promise used to return the URI of the file created.| - Error | Error Info| Error Code|Description| diff --git a/en/application-dev/reference/apis/js-apis-formbindingdata.md b/en/application-dev/reference/apis/js-apis-formbindingdata.md index 5f92677ec4a9856d96bc78b8787059ad5fb180ac..622f78b73e55afbe4fdcf8b342597b3ba44edeeb 100644 --- a/en/application-dev/reference/apis/js-apis-formbindingdata.md +++ b/en/application-dev/reference/apis/js-apis-formbindingdata.md @@ -1,6 +1,7 @@ # FormBindingData -> ![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. ## Modules to Import @@ -38,12 +39,20 @@ Creates a **FormBindingData** object. **Example** ```js - let fd = fileio.openSync(path); - let obj = { - "temperature": "21°", - "formImages": {"image": fd} - }; - let formBindingDataObj = formBindingData.createFormBindingData(obj); + import featureAbility from '@ohos.ability.featureAbility'; + import fileio from '@ohos.fileio'; + let context=featureAbility.getContext(); + context.getOrCreateLocalDir((err,data)=>{ + let path=data+"/xxx.jpg"; + let fd = fileio.openSync(path); + let obj = { + "temperature": "21°", + "formImages": {"image": fd} + }; + let formBindingDataObj = formBindingData.createFormBindingData(obj); + }) + + ``` ## Attributes diff --git a/en/application-dev/reference/apis/js-apis-formextension.md b/en/application-dev/reference/apis/js-apis-formextension.md index 0329e0cf3595887133d17c9af400df4b916d7845..b758b2f8e46d2bc4df93d94546f36c0caff4c960 100644 --- a/en/application-dev/reference/apis/js-apis-formextension.md +++ b/en/application-dev/reference/apis/js-apis-formextension.md @@ -1,7 +1,9 @@ # 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. +> **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. @@ -21,7 +23,7 @@ None | Name | Type | Readable| Writable| Description | | ------- | ------------------------------------------------------- | ---- | ---- | --------------------------------------------------- | -| context | [FormExtensionContext](js-apis-formextensioncontext.md) | Yes | No | Context of the **FormExtension**. This class is inherited from **ExtensionContext**.| +| context | [FormExtensionContext](js-apis-formextensioncontext.md) | Yes | No | Context of the **FormExtension**. This context is inherited from **ExtensionContext**.| ## onCreate @@ -227,7 +229,7 @@ Called when the configuration of the environment where the ability is running is onAcquireFormState?(want: Want): formInfo.FormState; -Used by the widget provider to receive the widget state query request. By default, the initial widget state is returned. +Called when the widget provider receives the status query result of a specified service widget. By default, the initial state is returned. **System capability**: SystemCapability.Ability.Form diff --git a/en/application-dev/reference/apis/js-apis-formextensioncontext.md b/en/application-dev/reference/apis/js-apis-formextensioncontext.md index a3aa439469ceee6234c7b4731a1804e2b44a61f6..4e877102c65aaf630ee5d5e12eff7d3c9e611b42 100644 --- a/en/application-dev/reference/apis/js-apis-formextensioncontext.md +++ b/en/application-dev/reference/apis/js-apis-formextensioncontext.md @@ -1,7 +1,9 @@ # 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. +> **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 **FormExtension**. This class is inherited from **ExtensionContext**. diff --git a/en/application-dev/reference/apis/js-apis-formhost.md b/en/application-dev/reference/apis/js-apis-formhost.md index 5c012bf525f59b08454fd7aa0886a5a0ed419d0e..91ea521d2bcdece8aa8b3f7b4fc7c278db4c2ba1 100644 --- a/en/application-dev/reference/apis/js-apis-formhost.md +++ b/en/application-dev/reference/apis/js-apis-formhost.md @@ -1,6 +1,7 @@ # FormHost -> **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. Provides APIs related to the widget host. diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index 7d4694bfa7cac837438ecd4f38a9f414316e92e0..01a012065ab52ac2e7a1dc781b608ec865394c31 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -1,5 +1,6 @@ # Geolocation +Location services provide basic functions such as GNSS positioning, network positioning, geocoding, reverse geocoding, country code and geofencing. > ![icon-note.gif](public_sys-resources/icon-note.gif) **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. @@ -695,7 +696,7 @@ This is a system API and cannot be called by third-party applications. disableLocation(callback: AsyncCallback<boolean>) : void; -Enables the location service. This API uses an asynchronous callback to return the result. +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. @@ -722,7 +723,7 @@ This is a system API and cannot be called by third-party applications. disableLocation() : Promise<boolean> -Enables the location service. This API uses a promise to return the result. +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. diff --git a/en/application-dev/reference/apis/js-apis-hashmap.md b/en/application-dev/reference/apis/js-apis-hashmap.md index 434f68b4b0324fe381961d64a00babcbba7d1d98..d1ac45e3bd10590be109ded2095405e4dee962de 100644 --- a/en/application-dev/reference/apis/js-apis-hashmap.md +++ b/en/application-dev/reference/apis/js-apis-hashmap.md @@ -1,27 +1,32 @@ # Nonlinear Container HashMap -> ![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. +**HashMap** is a map implemented based on the array, linked list, and red-black tree. It provides efficient data query, insertion, and removal. The elements in a **HashMap** instance are mappings of key-value pairs. Each key must be unique and have only one value. + +**HashMap** is faster in accessing data than **[TreeMap](js-apis-treemap.md)**, because the former accesses the keys based on the hash codes, whereas the latter stores and accesses the keys in sorted order. + +**[HashSet](js-apis-hashset.md)** is implemented based on **HashMap**. The input parameter of **HashMap** consists of **key** and **value**. In **HashSet**, only the **value** object is processed. + +**Recommended use case**: Use **HashMap** when you need to quickly access, remove, and insert key-value pairs. ## Modules to Import ```ts -import HashMap from '@ohos.util.HashMap' +import HashMap from '@ohos.util.HashMap'; ``` -## System Capabilities - -SystemCapability.Utils.Lang - ## HashMap - ### Attributes +**System capability**: SystemCapability.Utils.Lang + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Number of entries in a hash map (called container later).| +| length | number | Yes| No| Number of elements in a hash map (called container later).| ### constructor @@ -30,6 +35,8 @@ constructor() A constructor used to create a **HashMap** instance. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -41,7 +48,9 @@ let hashMap = new HashMap(); isEmpty(): boolean -Checks whether this container is empty (contains no entry). +Checks whether this container is empty (contains no element). + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -63,11 +72,13 @@ hasKey(key: K): boolean Checks whether this container contains the specified key. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key to check.| +| key | K | Yes| Target key.| **Return value** @@ -91,11 +102,13 @@ hasValue(value: V): boolean Checks whether this container contains the specified value. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | Yes| Value to check.| +| value | V | Yes| Target value.| **Return value** @@ -119,11 +132,13 @@ get(key: K): V Obtains the value of the specified key in this container. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key to query.| +| key | K | Yes| Target key.| **Return value** @@ -145,13 +160,15 @@ let result = hashMap.get("sdfs"); setAll(map: HashMap): void -Adds all entries in a **HashMap** instance to this container. +Adds all elements in a **HashMap** instance to this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| map | HashMap | Yes| **HashMap** instance whose entries are to be added to the current container.| +| map | HashMap | Yes| **HashMap** instance whose elements are to be added to the current container.| **Example** @@ -168,20 +185,22 @@ hashMap.setAll(newHashMap); set(key: K, value: V): Object -Adds an entry to this container. +Adds an element to this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key of the entry to add.| -| value | V | Yes| Value of the entry to add.| +| key | K | Yes| Key of the target element.| +| value | V | Yes| Value of the element.| **Return value** | Type| Description| | -------- | -------- | -| Object | Container that contains the new entry.| +| Object | Container that contains the new element.| **Example** @@ -195,19 +214,21 @@ let result = hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); remove(key: K): V -Removes an entry with the specified key from this container. +Removes an element with the specified key from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key of the entry to remove.| +| key | K | Yes| Key of the target element.| **Return value** | Type| Description| | -------- | -------- | -| V | Value of the entry removed.| +| V | Value of the element.| **Example** @@ -225,6 +246,8 @@ clear(): void Clears this container and sets its length to **0**. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -239,7 +262,9 @@ hashMap.clear(); keys(): IterableIterator<K> -Obtains an iterator that contains all the entries in this container. +Obtains an iterator that contains all the elements in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -256,7 +281,7 @@ hashMap.set("sdfs", 356); let iter = hashMap.keys(); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value:" + temp); temp = iter.next().value; } ``` @@ -268,6 +293,8 @@ values(): IterableIterator<V> Obtains an iterator that contains all the values in this container. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -283,7 +310,7 @@ hashMap.set("sdfs", 356); let iter = hashMap.values(); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value:" + temp); temp = iter.next().value; } ``` @@ -293,20 +320,22 @@ while(temp != undefined) { replace(key: K, newValue: V): boolean -Replaces an entry in this container. +Replaces an element in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key of the entry to replace.| -| newValue | V | Yes| New value of the entry.| +| key | K | Yes| Key of the target element.| +| newValue | V | Yes| New value of the element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the entry is replaced successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is replaced successfully; returns **false** otherwise.| **Example** @@ -321,20 +350,22 @@ let result = hashMap.replace("sdfs", 357); forEach(callbackfn: (value?: V, key?: K, map?: HashMap) => void, thisArg?: Object): void -Uses a callback to traverse the entries in this container and obtain their position indexes. +Uses a callback to traverse the elements in this container and obtain their position indexes. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.| +| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | No| Value of the entry that is currently traversed.| -| key | K | No| Key of the entry that is currently traversed.| +| value | V | No| Value of the element that is currently traversed.| +| key | K | No| Key of the element that is currently traversed.| | map | HashMap | No| Instance that invokes the **forEach** method.| **Example** @@ -344,7 +375,7 @@ let hashMap = new HashMap(); hashMap.set("sdfs", 123); hashMap.set("dfsghsf", 357); hashMap.forEach((value, key) => { - console.log(value, key); + console.log("value:" + value, key); }); ``` @@ -353,7 +384,9 @@ hashMap.forEach((value, key) => { entries(): IterableIterator<[K, V]> -Obtains an iterator that contains all the entries in this container. +Obtains an iterator that contains all the elements in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -370,8 +403,8 @@ hashMap.set("sdfs", 356); let iter = hashMap.entries(); let temp = iter.next().value; while(temp != undefined) { - console.log(temp[0]); - console.log(temp[1]); + console.log("key:" + temp[0]); + console.log("value:" + temp[1]); temp = iter.next().value; } ``` @@ -383,6 +416,8 @@ while(temp != undefined) { Obtains an iterator, each item of which is a JavaScript object. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -397,16 +432,16 @@ hashMap.set("sdfs", 356); // Method 1: for (let item of hashMap) { - console.log("key: " + item[0]); - console.log("value: " + item[1]); + console.log("key:" + item[0]); + console.log("value:" + item[1]); } // Method 2: let iter = hashMap[Symbol.iterator](); let temp = iter.next().value; while(temp != undefined) { - console.log(temp[0]); - console.log(temp[1]); + console.log("key:" + temp[0]); + console.log("value:" + temp[1]); temp = iter.next().value; } ``` diff --git a/en/application-dev/reference/apis/js-apis-hashset.md b/en/application-dev/reference/apis/js-apis-hashset.md index 605aa184364b76c5695390db18d63bcf6cbff689..85bbfa2719412099c1d051de61b3c39363872b27 100644 --- a/en/application-dev/reference/apis/js-apis-hashset.md +++ b/en/application-dev/reference/apis/js-apis-hashset.md @@ -1,8 +1,14 @@ # Nonlinear Container HashSet -> ![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. +**HashSet** is implemented based on [HashMap](js-apis-hashmap.md). In **HashSet**, only the **value** object is processed. + +Unlike [TreeSet](js-apis-treeset.md), which stores and accesses data in sorted order, **HashSet** stores data in a random order. This means that **HashSet** may use a different order when storing and accessing elements. Both of them allows only unique elements. However, null values are allowed in **HashSet**, but not allowed in **TreeSet**. + +**Recommended use case**: Use **HashSet** when you need a set that has only unique elements or need to deduplicate a set. ## Modules to Import @@ -10,18 +16,15 @@ import HashSet from '@ohos.util.HashSet'; ``` -## System Capabilities - -SystemCapability.Utils.Lang - ## HashSet - ### Attributes +**System capability**: SystemCapability.Utils.Lang + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Number of entries in a hash set (called container later).| +| length | number | Yes| No| Number of elements in a hash set (called container later).| ### constructor @@ -30,6 +33,8 @@ constructor() A constructor used to create a **HashSet** instance. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -41,7 +46,9 @@ let hashSet = new HashSet(); isEmpty(): boolean -Checks whether this container is empty (contains no entry). +Checks whether this container is empty (contains no element). + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -61,19 +68,21 @@ let result = hashSet.isEmpty(); has(value: T): boolean -Checks whether this container contains the specified entry. +Checks whether this container contains the specified element. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Entry to check.| +| value | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the specified entry is contained; returns **false** otherwise.| +| boolean | Returns **true** if the specified element is contained; returns **false** otherwise.| **Example** @@ -89,19 +98,21 @@ let result1 = hashSet.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); add(value: T): boolean -Adds an entry to this container. +Adds an element to this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Entry to add.| +| value | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the entry is added successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is added successfully; returns **false** otherwise.| **Example** @@ -115,19 +126,21 @@ let result = hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); remove(value: T): boolean -Removes an entry from this container. +Removes an element from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Entry to remove.| +| value | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the entry is removed successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is removed successfully; returns **false** otherwise.| **Example** @@ -145,6 +158,8 @@ clear(): void Clears this container and sets its length to **0**. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -161,6 +176,8 @@ values(): IterableIterator<T> Obtains an iterator that contains all the values in this container. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -176,7 +193,7 @@ hashSet.add("sdfs"); let iter = hashSet.values(); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value:" + temp); temp = iter.next().value; } ``` @@ -186,20 +203,22 @@ while(temp != undefined) { forEach(callbackfn: (value?: T, key?: T, set?: HashSet<T>) => void, thisArg?: Object): void -Uses a callback to traverse the entries in this container and obtain their position indexes. +Uses a callback to traverse the elements in this container and obtain their position indexes. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.| +| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | No| Value of the entry that is currently traversed.| -| key | T | No| Key of the entry that is currently traversed (same as **value**).| +| value | T | No| Value of the element that is currently traversed.| +| key | T | No| Key of the element that is currently traversed (same as **value**).| | set | HashSet<T> | No| Instance that invokes the **forEach** method.| **Example** @@ -209,7 +228,7 @@ let hashSet = new HashSet(); hashSet.add("sdfs"); hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); hashSet.forEach((value, key) => { - console.log(value, key); + console.log("value:" + value, key); }); ``` @@ -217,7 +236,9 @@ hashSet.forEach((value, key) => { ### entries entries(): IterableIterator<[T, T]> -Obtains an iterator that contains all the entries in this container. +Obtains an iterator that contains all the elements in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -234,8 +255,8 @@ hashSet.add("sdfs"); let iter = hashSet.entries(); let temp = iter.next().value; while(temp != undefined) { - console.log(temp[0]); - console.log(temp[1]); + console.log("key:" + temp[0]); + console.log("value:" + temp[1]); temp = iter.next().value; } ``` @@ -247,6 +268,8 @@ while(temp != undefined) { Obtains an iterator, each item of which is a JavaScript object. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -269,7 +292,7 @@ for (let item of hashSet) { let iter = hashSet[Symbol.iterator](); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value: " + temp); temp = iter.next().value; } ``` diff --git a/en/application-dev/reference/apis/js-apis-hichecker.md b/en/application-dev/reference/apis/js-apis-hichecker.md index 1095d5f9aa56c1077c8db6ba2fcb81ea29642309..ec2833f49fca4f4f570ac45f25cdefaa5741702e 100644 --- a/en/application-dev/reference/apis/js-apis-hichecker.md +++ b/en/application-dev/reference/apis/js-apis-hichecker.md @@ -21,15 +21,15 @@ Provides the constants of all rule types. | Name | Type| Description | | ---------------------------------- | -------- | ------------------------------------------------------ | -| RULE_CAUTION_PRINT_LOG | bigInt | Alarm rule, which is programmed to print a log when an alarm is generated. | -| RULE_CAUTION_TRIGGER_CRASH | bigInt | Alarm rule, which is programmed to force the application to exit when an alarm is generated. | -| RULE_THREAD_CHECK_SLOW_PROCESS | bigInt | Caution rule, which is programmed to detect whether any time-consuming function is invoked. | -| RULE_CHECK_ABILITY_CONNECTION_LEAK | bigInt | Caution rule, which is programmed to detect whether ability leakage has occurred. | +| RULE_CAUTION_PRINT_LOG | bigint | Alarm rule, which is programmed to print a log when an alarm is generated. | +| RULE_CAUTION_TRIGGER_CRASH | bigint | Alarm rule, which is programmed to force the application to exit when an alarm is generated. | +| RULE_THREAD_CHECK_SLOW_PROCESS | bigint | Caution rule, which is programmed to detect whether any time-consuming function is invoked. | +| RULE_CHECK_ABILITY_CONNECTION_LEAK | bigint | Caution rule, which is programmed to detect whether ability leakage has occurred. | ## hichecker.addRule -addRule(rule: bigInt): void +addRule(rule: bigint): void Adds one or more rules. HiChecker detects unexpected operations or gives feedback based on the added rules. @@ -39,7 +39,7 @@ Adds one or more rules. HiChecker detects unexpected operations or gives feedbac | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| rule | bigInt | Yes | Rule to be added.| +| rule | bigint | Yes | Rule to be added.| **Example** @@ -54,7 +54,7 @@ hichecker.addRule( ## hichecker.removeRule -removeRule(rule: bigInt): void +removeRule(rule: bigint): void Removes one or more rules. The removed rules will become ineffective. @@ -64,7 +64,7 @@ Removes one or more rules. The removed rules will become ineffective. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| rule | bigInt | Yes | Rule to be removed.| +| rule | bigint | Yes | Rule to be removed.| **Example** @@ -79,7 +79,7 @@ hichecker.removeRule( ## hichecker.getRule -getRule(): bigInt +getRule(): bigint Obtains a collection of thread, process, and alarm rules that have been added. @@ -89,7 +89,7 @@ Obtains a collection of thread, process, and alarm rules that have been added. | Type | Description | | ------ | ---------------------- | -| bigInt | Collection of added rules.| +| bigint | Collection of added rules.| **Example** @@ -98,12 +98,12 @@ Obtains a collection of thread, process, and alarm rules that have been added. hichecker.addRule(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // Obtain the collection of added rules. -hichecker.getRule(); // Return 1n. +hichecker.getRule(); // return 1n; ``` ## hichecker.contains -contains(rule: bigInt): boolean +contains(rule: bigint): boolean Checks whether the specified rule exists in the collection of added rules. If the rule is of the thread level, this operation is performed only on the current thread. @@ -113,13 +113,13 @@ Checks whether the specified rule exists in the collection of added rules. If th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| rule | bigInt | Yes | Rule to be checked.| +| rule | bigint | Yes | Rule to be checked.| **Return value** | Type | Description | | ------- | ---------------------------------------------------------- | -| boolean | Returns **true** if the rule exists in the collection of added rules; returns **false** otherwise. | +| boolean | Returns **true** if the rule exists in the collection of added rules; returns **false** otherwise.| **Example** @@ -128,6 +128,6 @@ Checks whether the specified rule exists in the collection of added rules. If th hichecker.addRule(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // Check whether the added rule exists in the collection of added rules. -hichecker.contains(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // Return true -hichecker.contains(hichecker.RULE_CAUTION_PRINT_LOG); // Return false +hichecker.contains(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // return true; +hichecker.contains(hichecker.RULE_CAUTION_PRINT_LOG); // return false; ``` diff --git a/en/application-dev/reference/apis/js-apis-hilog.md b/en/application-dev/reference/apis/js-apis-hilog.md index 107d3419b8a8b2840d54b90c5e239ea2fea85ac3..4d45271a8791a8370ed4950c75ac96c0fb408b8c 100644 --- a/en/application-dev/reference/apis/js-apis-hilog.md +++ b/en/application-dev/reference/apis/js-apis-hilog.md @@ -1,7 +1,6 @@ # HiLog The HiLog subsystem allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs. -This document describes only API functions. For details about log printing requirements, see [Logging Guide](../../../contribute/OpenHarmony-Log-guide.md). > **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-hisysevent.md b/en/application-dev/reference/apis/js-apis-hisysevent.md new file mode 100644 index 0000000000000000000000000000000000000000..5564b1a7fc8024284fabf6ada9efaa08f8d0cb73 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-hisysevent.md @@ -0,0 +1,345 @@ +# System Event Logging + +Provides system event logging APIs for system HAP applications. + +> **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. + + +## Modules to Import + +```js +import hiSysEvent from '@ohos.hiSysEvent'; +``` + +## EventType + +Enumerates event types. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| FAULT | 1 | Error event.| +| STATISTIC | 2 | Statistic event.| +| SECURITY | 3 | Security event.| +| BEHAVIOR | 4 | User behavior event.| + +## SysEventInfo + +Defines a system event. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| domain | string | Yes| Event domain.| +| name | string | Yes| Event name.| +| eventType | [EventType](#eventtype) | Yes| Event type.| +| params | object | No| Event parameters.| + + +## hiSysEvent.write + +write(info: SysEventInfo, callback: AsyncCallback<void>): void + +Writes event information to the event file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | ------------------------------------------------------------ | +| info | [SysEventInfo](#syseventinfo) | Yes| System event information.| +| callback | AsyncCallback<void> | Yes| Callback used to process the received return value.
- Value **0**: The event verification is successful, and the event will be written to the event file asynchronously.
- A value greater than **0**: Invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
- A value smaller than **0**: The event parameter verification fails, and the event will not be written to the event file.| + +**Example** + +```js +import hiSysEvent from '@ohos.hiSysEvent'; + +hiSysEvent.write({ + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: { + PID: 487, + UID: 103, + PACKAGE_NAME: "com.ohos.hisysevent.test", + PROCESS_NAME: "syseventservice", + MSG: "no msg." + } +}, (err, val) => { + // do something here. +}) +``` + + +## hiSysEvent.write + +write(info: SysEventInfo): Promise<void> + +Writes event information to the event file. This API uses a promise to return the result. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +**Parameters** + +| Name | Type | Mandatory| Description| +| --------- | ----------------------- | ---- | --------------- | +| eventType | [EventType](#eventtype) | Yes | Application event type.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise used to return the result. Depending on whether event writing is successful, you can use the **then()** or **catch()** method to process the callback.| + +**Example** + +```js +import hiSysEvent from '@ohos.hiSysEvent'; + +hiSysEvent.write({ + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: { + PID: 487, + UID: 103, + PACKAGE_NAME: "com.ohos.hisysevent.test", + PROCESS_NAME: "syseventservice", + MSG: "no msg." + } +}).then( + (val) => { + // do something here. + } +).catch( + (err) => { + // do something here. + } +) +``` + +## RuleType + +Enumerates matching rule types. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| WHOLE_WORD | 1 | Whole word matching.| +| PREFIX | 2 | Prefix matching.| +| REGULAR | 3 | Regular expression matching.| + +## WatchRule + +Defines rules for event subscription. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| domain | string | Yes| Event domain.| +| name | string | Yes| Event name.| +| tag | string | No| Event tag.| +| ruleType | [RuleType](#ruletype) | Yes| Matching rule type.| + +## Watcher + +Defines a watcher for event subscription. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| rules | [WatchRule](#watchrule)[] | Yes| Array of matching rules for event subscription.| +| onEvent | function | Yes| Callback for event subscription: (info: [SysEventInfo](#syseventinfo)) => void| +| onServiceDied | function | Yes| Callback for disabling of event subscription: () => void| + +## hiSysEvent.addWatcher + +addWatcher(watcher: Watcher): number + +Adds a watcher for event subscription. + +**Required permission**: ohos.permission.READ_DFX_SYSEVENT + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------ | ----------------------------- | ---- | ------------------------ | +| watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| + +**Return value** + +| Type | Description| +| ------- | -------------------------------------------------- | +| number | Event subscription result.
- **0**: Event subscription is successful.
- A value smaller than **0**: Event subscription has failed.| + +**Example** + +```js +import hiSysEvent from '@ohos.hiSysEvent'; + +let watcher = { + rules: [{ + domain: "RELIABILITY", + name: "STACK", + tag: "STABILITY", + ruleType: hiSysEvent.RuleType.WHOLE_WORD, + }], + onEvent: (info) => { + // do something here. + }, + onServiceDied: () => { + // do something here. + } +} +let ret = hiSysEvent.addWatcher(watcher) +``` + +## hiSysEvent.removeWatcher + +removeWatcher(wathcer: Watcher): number + +Removes a watcher used for event subscription. + +**Required permission**: ohos.permission.READ_DFX_SYSEVENT + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | ------------------------ | +| watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| + +**Return value** + +| Type | Description| +| ------- | ----------------------------------------------------------- | +| number | Result of removing the watcher.
- **0**: Removing the watcher is successful.
- A value smaller than **0**: Removing the watcher has failed.| + +**Example** + +```js +import hiSysEvent from '@ohos.hiSysEvent'; + +let watcher = { + rules: [{ + domain: "RELIABILITY", + name: "STACK", + tag: "STABILITY", + ruleType: hiSysEvent.RuleType.WHOLE_WORD, + }], + onEvent: (info) => { + // do something here. + }, + onServiceDied: () => { + // do something here. + } +} +let ret = hiSysEvent.addWatcher(watcher) +hiSysEvent.removeWatcher(watcher) +``` + +## QueryArg + +Defines arguments for event query. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| beginTime | number | Yes| Start time (13-digit timestamp) for event query.| +| endTime | number | Yes| End time (13-digit timestamp) for event query.| +| maxEvents | number | Yes| Maximum number of events that can be queried.| + +## QueryRule + +Defines rules for event query. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| domain | string | Yes| Event domain.| +| names | string[] | Yes| Array of event names.| + +## Querier + +Defines an event query instance. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| onQuery | function | Yes| Callback of queried events: (infos: [SysEventInfo](#syseventinfo)[], seqs: number[]) => void| +| onComplete | function | Yes| Callback of query result statistics: (reason: number, total: number) => void| + +## hiSysEvent.query + +query(queryArg: QueryArg, rules: QueryRule[], querier: Querier): number + +Queries system events. + +**Required permission**: ohos.permission.READ_DFX_SYSEVENT + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------ | ----------------------------- | ---- | ------------------------ | +| queryArg | [QueryArg](#queryarg) | Yes | Arguments for event query.| +| rules | [QueryRule](#queryrule)[] | Yes | Array of event query rules.| +| querier | [Querier](#querier) | Yes | Event query instance.| + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------------------- | +| number | Event query result.
- **0**: Event query is successful.
- A value smaller than **0**: Event query has failed.| + +**Example** + +```js +import hiSysEvent from '@ohos.hiSysEvent'; + +hiSysEvent.write({ + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: { + PID: 487, + UID: 103, + PACKAGE_NAME: "com.ohos.hisysevent.test", + PROCESS_NAME: "syseventservice", + MSG: "no msg." + } +}, (err, val) => { + // do something here. +}) +hiSysEvent.query({ + beginTime: -1, + endTime: -1, + maxEvents: 5, +}, [{ + domain: "RELIABILITY", + names: ["STACK"], +}], { + onQuery: function (infos, seqs) { + // do something here. + }, + onComplete: function(reason, total) { + // do something here. + } +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index f42f8502d5a96024c64c55996bd2a17eba939af9..d06667da7dc1cd4efce41464968cd975309418d7 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -702,7 +702,7 @@ Defines the measurement unit information. ### unitConvert8+ -unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string +static unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string Converts one measurement unit into another and formats the unit based on the specified locale and style. @@ -825,7 +825,7 @@ Obtains the index of a text object. ### isDigit8+ -isDigit(char: string): boolean +static isDigit(char: string): boolean Checks whether the input character string is composed of digits. @@ -849,7 +849,7 @@ Checks whether the input character string is composed of digits. ### isSpaceChar8+ -isSpaceChar(char: string): boolean +static isSpaceChar(char: string): boolean Checks whether the input character is a space. @@ -873,7 +873,7 @@ Checks whether the input character is a space. ### isWhitespace8+ -isWhitespace(char: string): boolean +static isWhitespace(char: string): boolean Checks whether the input character is a white space. @@ -897,7 +897,7 @@ Checks whether the input character is a white space. ### isRTL8+ -isRTL(char: string): boolean +static isRTL(char: string): boolean Checks whether the input character is of the right to left (RTL) language. @@ -921,7 +921,7 @@ Checks whether the input character is of the right to left (RTL) language. ### isIdeograph8+ -isIdeograph(char: string): boolean +static isIdeograph(char: string): boolean Checks whether the input character is an ideographic character. @@ -945,7 +945,7 @@ Checks whether the input character is an ideographic character. ### isLetter8+ -isLetter(char: string): boolean +static isLetter(char: string): boolean Checks whether the input character is a letter. @@ -969,7 +969,7 @@ Checks whether the input character is a letter. ### isLowerCase8+ -isLowerCase(char: string): boolean +static isLowerCase(char: string): boolean Checks whether the input character is a lowercase letter. @@ -993,7 +993,7 @@ Checks whether the input character is a lowercase letter. ### isUpperCase8+ -isUpperCase(char: string): boolean +static isUpperCase(char: string): boolean Checks whether the input character is an uppercase letter. @@ -1017,7 +1017,7 @@ Checks whether the input character is an uppercase letter. ### getType8+ -getType(char: string): string +static getType(char: string): string Obtains the type of the input character string. @@ -1124,7 +1124,7 @@ Obtains the position of the [BreakIterator](#breakiterator8) object in the text ``` var iterator = i18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - breakIter.current(); // 0 + iterator.current(); // 0 ``` @@ -1145,7 +1145,7 @@ Puts the [BreakIterator](#breakiterator8) object to the first text boundary, whi ``` var iterator = i18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - breakIter.first(); // 0 + iterator.first(); // 0 ``` diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 5b564c7addd10b39e5873bf50faa84efc9ff1ad6..7369fcdb2e2415913fb3b197aaa8d209a9fee4ef 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -1388,7 +1388,7 @@ Defines image decoding options. | desiredSize | [Size](#size) | Yes | Yes | Expected output size. | | desiredRegion | [Region](#region7) | Yes | Yes | Region to decode. | | desiredPixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format for decoding.| -| index | numer | Yes | Yes | Index of the image to decode. | +| index | number | Yes | Yes | Index of the image to decode. | ## Region7+ diff --git a/en/application-dev/reference/apis/js-apis-inputconsumer.md b/en/application-dev/reference/apis/js-apis-inputconsumer.md index 3e9a9af045b92543f5e9221b5ffa199c4bf9b054..8a458433505279ac0bd72b1d418972b409bd59f9 100644 --- a/en/application-dev/reference/apis/js-apis-inputconsumer.md +++ b/en/application-dev/reference/apis/js-apis-inputconsumer.md @@ -1,9 +1,10 @@ # Combination Key -> ![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. -> +> > - The APIs of this module are system APIs and cannot be called by third-party applications. @@ -17,66 +18,71 @@ import inputConsumer from '@ohos.multimodalInput.inputConsumer'; ## inputConsumer.on -on(type: "key", keyOption: KeyOption, callback: Callback<KeyOption>): void +on(type: "key", keyOptions: KeyOptions, callback: Callback): void -Enables listening for combination key events. When a combination key event that meets the specified conditions occurs, **keyOption** will be passed as an input parameter to **callback**. +Enables listening for combination key events. When a combination key event that meets the specified conditions occurs, **keyOptions** will be passed as an input parameter to **callback**. **System capability**: SystemCapability.MultimodalInput.Input.InputConsumer - **Parameters** - | Name | Type | Mandatory | Description | +**Parameters** + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the key input event to listen for. Only **key** is supported. | -| keyOption | [KeyOption](#keyoption) | Yes | Key option, which specifies the condition for combination key input. | -| callback | Callback<KeyOption> | Yes | Callback function. When a key input event that meets the specified options occurs, **keyOption** will be passed as an input parameter to **callback**. | +| type | string | Yes| Type of the key input event to listen for. Only **key** is supported.| +| keyOptions | [keyOptions](#keyOptions) | Yes| Key option, which specifies the condition for combination key input.| +| callback | KeyOptions | Yes| Callback used to return the result.
When a key input event that meets the specified options occurs, **keyOptions** will be passed as an input parameter to **callback**.| - **Example** +**Example** ``` -let keyOption = {preKeys: [], finalKey: 3, isFinalKeyDown: true, finalKeyDownDuration: 0} -let callback = function(keyOption) { - console.info("preKeys: " + keyOption.preKeys, "finalKey: " + keyOption.finalKey, - "isFinalKeyDown: " + keyOption.isFinalKeyDown, "finalKeyDownDuration: " + keyOption.finalKeyDownDuration) +let keyOptions = {preKeys: [], finalKey: 3, isFinalKeyDown: true, finalKeyDownDuration: 0} +let callback = function(keyOptions) { + console.info("preKeys: " + keyOptions.preKeys, "finalKey: " + keyOptions.finalKey, + "isFinalKeyDown: " + keyOptions.isFinalKeyDown, "finalKeyDownDuration: " + keyOptions.finalKeyDownDuration) } -inputConsumer.on('key', keyOption, callback); +inputConsumer.on('key', keyOptions, callback); ``` ## inputConsumer.off -off(type: "key", keyOption: KeyOption, callback: Callback<KeyOption>): void +off(type: "key", keyOptions: KeyOptions, callback?: Callback): void Stops listening for combination key events. **System capability**: SystemCapability.MultimodalInput.Input.InputConsumer - **Parameters** - | Name | Type | Mandatory | Description | +**Parameters** + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the key input event to listen for. Only **key** is supported. | -| keyOption | [KeyOption](#keyoption) | Yes | Key option passed to the key input event when listening starts. | -| callback | Callback<KeyOption> | Yes | Callback function passed to the key input event with the key option when listening starts. | +| type | string | Yes| Type of the key input event to listen for. Only **key** is supported.| +| keyOptions | [keyOptions](#keyOptions) | Yes| Key options passed to the key input event when listening starts.| +| callback | Callback | Yes| Callback function passed to the key input event with **keyOptions** when listening starts.| - **Example** +**Example** ``` -let keyOption = {preKeys: [], finalKey: 3, isFinalKeyDown: true, finalKeyDownDuration: 0} -let callback = function(keyOption) { - console.info("preKeys: " + keyOption.preKeys, "finalKey: " + keyOption.finalKey, - "isFinalKeyDown: " + keyOption.isFinalKeyDown, "finalKeyDownDuration: " + keyOption.finalKeyDownDuration) +let keyOptions = {preKeys: [], finalKey: 3, isFinalKeyDown: true, finalKeyDownDuration: 0} +let callback = function(keyOptions) { + console.info("preKeys: " + keyOptions.preKeys, "finalKey: " + keyOptions.finalKey, + "isFinalKeyDown: " + keyOptions.isFinalKeyDown, "finalKeyDownDuration: " + keyOptions.finalKeyDownDuration) } -inputConsumer.off('key', keyOption, callback); +inputConsumer.off('key', keyOptions, callback); ``` -## KeyOption +## keyOptions Defines the key options that are met when a combination key input event occurs. - **System capability**: SystemCapability.MultimodalInput.Input.InputConsumer - | Name | Type | Mandatory | Description | +**System capability**: SystemCapability.MultimodalInput.Input.InputConsumer + +**Parameters** + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| preKeys | Array | Yes | Array of precedent keys. This parameter can be left empty. There is no requirement on the sequence of precedent keys. | -| finalKey | Number | Yes | Final key in the combination key. This parameter cannot be left blank. | -| isFinalKeyDown | boolean | Yes | Indicates whether the final key is pressed or released. By default, the final key is pressed. | -| finalKeyDownDuration | Number | Yes | Duration for pressing the final key. By default, there is no requirement on the duration. | +| preKeys | Array | Yes| Array of precedent keys. This parameter can be left empty. There is no requirement on the sequence of precedent keys.| +| finalKey | Number | Yes| Final key in the combination key. This parameter cannot be left blank.| +| isFinalKeyDown | boolean | Yes| Whether the final key is pressed or released. By default, the final key is pressed.| +| finalKeyDownDuration | Number | Yes| Duration for pressing the final key. By default, there is no requirement on the duration.| diff --git a/en/application-dev/reference/apis/js-apis-inputdevice.md b/en/application-dev/reference/apis/js-apis-inputdevice.md index 7f164c33cb01561b88cf01e53879cfffd519477a..c47a977b1f2b1559488b6f6602a6ed116ad88197 100644 --- a/en/application-dev/reference/apis/js-apis-inputdevice.md +++ b/en/application-dev/reference/apis/js-apis-inputdevice.md @@ -25,10 +25,10 @@ Enables listening for hot swap events of an input device. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | -------------------- | -| type | string | Yes | Event type of the input device. | -| listener | Callback<[DeviceListener](#devicelistener9+)> | Yes | Listener for events of the input device.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------- | +| type | string | Yes | Event type of the input device. | +| listener | Callback<[DeviceListener](#devicelistener9+)> | Yes | Listener for events of the input device.| **Example** @@ -36,12 +36,12 @@ Enables listening for hot swap events of an input device. let isPhysicalKeyboardExist = true; inputDevice.on("change", (data) => { console.log("type: " + data.type + ", deviceId: " + data.deviceId); - inputDevice.getKeyboardType(data.deviceId, (ret) => { + inputDevice.getKeyboardType(data.deviceId, (err, ret) => { console.log("The keyboard type of the device is: " + ret); - if (ret == 2 && data.type == 'add') { + if (ret == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') { // The physical keyboard is connected. isPhysicalKeyboardExist = true; - } else if (ret == 2 && data.type == 'remove') { + } else if (ret == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'remove') { // The physical keyboard is disconnected. isPhysicalKeyboardExist = false; } @@ -60,20 +60,20 @@ Disables listening for hot swap events of an input device. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | -------------------- | -| type | string | Yes | Event type of the input device. | -| listener | Callback<[DeviceListener](#devicelistener9+)> | No | Listener for events of the input device.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------- | +| type | string | Yes | Event type of the input device. | +| listener | Callback<[DeviceListener](#devicelistener9+)> | No | Listener for events of the input device.| **Example** ```js -listener: function(data) { +function listener(data) { console.log("type: " + data.type + ", deviceId: " + data.deviceId); } // Disable this listener. -inputDevice.off("change", this.listener); +inputDevice.off("change", listener); // Disable all listeners. inputDevice.off("change"); @@ -104,7 +104,7 @@ inputDevice.getDeviceIds((ids)=>{ ## inputDevice.getDeviceIds -function getDeviceIds(): Promise<<Array<number>> +getDeviceIds(): Promise<Array<number>> Obtains the IDs of all input devices. This API uses a promise to return the result. @@ -112,8 +112,8 @@ Obtains the IDs of all input devices. This API uses a promise to return the resu **Return value** -| Parameter | Description | -| ------------------------- | ----------------------------- | +| Parameter | Description | +| ---------------------------------- | ------------------- | | Promise<Array<number>> | Promise used to return the result.| **Example** @@ -128,7 +128,7 @@ inputDevice.getDeviceIds().then((ids)=>{ getDevice(deviceId: number, callback: AsyncCallback<InputDeviceData>): void -Obtains the information about an input device. This API uses an asynchronous callback to return the result. +Obtains information about an input device. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice @@ -150,7 +150,7 @@ inputDevice.getDevice(1, (inputDevice)=>{ ## inputDevice.getDevice -function getDevice(deviceId: number): Promise<InputDeviceData> +getDevice(deviceId: number): Promise<InputDeviceData> Obtains information about an input device. This API uses a promise to return the result. @@ -158,14 +158,14 @@ Obtains information about an input device. This API uses a promise to return the **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ---------------------- | -| deviceId | number | Yes | ID of the input device.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------ | +| deviceId | number | Yes | ID of the input device.| **Return value** -| Parameter | Description | -| -------------------------------------------------- | ----------------------------- | +| Parameter | Description | +| ---------------------------------------- | ------------------- | | Promise<[InputDeviceData](#inputdevicedata)> | Promise used to return the result.| **Example** @@ -181,17 +181,17 @@ inputDevice.getDevice(1).then((inputDevice)=>{ supportKeys(deviceId: number, keys: Array<KeyCode>, callback: Callback<Array<boolean>>): void; -Checks whether an input device supports the specified key codes. This API uses an asynchronous callback to return the result. +Obtains the key codes supported by the input device. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | -| deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| -| keys | Array<KeyCode> | Yes | Key code to be queried. A maximum of five key codes can be specified. | -| callback | Callback<Array<boolean>> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------ | ---- | --------------------------------- | +| deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| +| keys | Array<KeyCode> | Yes | Key codes to be queried. A maximum of five key codes can be specified. | +| callback | Callback<Array<boolean>> | Yes | Callback used to return the result. | **Example** @@ -206,21 +206,21 @@ inputDevice.supportKeys(1, [17, 22, 2055], (ret)=>{ supportKeys(deviceId: number, keys: Array<KeyCode>): Promise<Array<boolean>>; -Checks whether an input device supports the specified key codes. This API uses a promise to return the result. +Obtains the key codes supported by the input device. This API uses a promise to return the result. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------------------------------------------ | -| deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| -| keys | Array<KeyCode> | Yes | Key code to be queried. A maximum of five key codes can be specified. | +| Name | Type | Mandatory | Description | +| -------- | -------------------- | ---- | --------------------------------- | +| deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| +| keys | Array<KeyCode> | Yes | Key codes to be queried. A maximum of five key codes can be specified. | **Return value** -| Parameter | Description | -| ----------------------------------- | ----------------------------- | +| Parameter | Description | +| ----------------------------------- | ------------------- | | Promise<Array<boolean>> | Promise used to return the result.| **Example** @@ -242,10 +242,10 @@ Obtains the keyboard type of an input device. This API uses an asynchronous call **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | -| deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| -| callback | AsyncCallback<[KeyboardType](#keyboardtype)> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------- | +| deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| +| callback | AsyncCallback<[KeyboardType](#keyboardtype)> | Yes | Callback used to return the result. | **Example** @@ -266,29 +266,29 @@ Obtains the keyboard type of an input device. This API uses a promise to return **Return value** -| Parameter | Description | -| -------------------------------------------- | ----------------------------- | +| Parameter | Description | +| ---------------------------------------- | ------------------- | | Promise<[KeyboardType](#keyboardtype)> | Promise used to return the result.| **Example** ```js // Query the keyboard type of the input device whose ID is 1. -inputDevice.getKeyboardType().then((ret)=>{ +inputDevice.getKeyboardType(1).then((ret)=>{ console.log("The keyboard type of the device is: " + ret); }) ``` ## DeviceListener9+ -Defines a listener for events of an input device. +Defines the information about an input device. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice -| Name | Type | Description | -| -------- | --------------------------- | ------------------------------------------------------------ | -| type | [ChangeType](#changetype) | 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.| +| Name | Type | Description | +| -------- | ------------------------- | --------------------------------- | +| type | [ChangeType](#changetype) | 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 @@ -296,18 +296,18 @@ Defines the information about an input device. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice -| Name | Type | Description | -| -------------------- | -------------------------------------- | ------------------------------------------------------------ | -| id | number | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| -| name | string | Name of the input device. | -| sources | Array<[SourceType](#sourcetype)> | Source types of the input device. For example, if a keyboard is attached with a touchpad, the device has two input sources: keyboard and touchpad.| -| axisRanges | Array<[axisRanges](#axisrange)> | Axis information of the input device. | -| bus9+ | number | Bus type of the input device. | -| product9+ | number | Product information of the input device. | -| vendor9+ | number | Vendor information of the input device. | -| version9+ | number | Version information of the input device. | -| phys9+ | string | Physical address of the input device. | -| uniq9+ | string | Unique ID of the input device. | +| Name | Type | Description | +| -------------------- | -------------------------------------- | ---------------------------------------- | +| id | number | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes. | +| name | string | Name of the input device. | +| sources | Array<[SourceType](#sourcetype)> | Source type of the input device. For example, if a keyboard is attached with a touchpad, the device has two input sources: keyboard and touchpad.| +| axisRanges | Array<[axisRanges](#axisrange)> | Axis information of the input device. | +| bus9+ | number | Bus type of the input device. | +| product9+ | number | Product information of the input device. | +| vendor9+ | number | Vendor information of the input device. | +| version9+ | number | Version information of the input device. | +| phys9+ | string | Physical address of the input device. | +| uniq9+ | string | Unique ID of the input device. | ## AxisType9+ @@ -315,17 +315,17 @@ Defines the axis type of an input device. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice -| Name | Type| Description | -| ----------- | -------- | ------------------- | -| touchMajor | string | touchMajor axis. | -| touchMinor | string | touchMinor axis. | -| toolMinor | string | toolMinor axis. | -| toolMajor | string | toolMajor axis. | -| orientation | string | Orientation axis.| -| pressure | string | Pressure axis. | -| x | string | X axis. | -| y | string | Y axis. | -| NULL | string | None. | +| Name | Type | Description | +| ----------- | ------ | --------------- | +| touchMajor | string | touchMajor axis. | +| touchMinor | string | touchMinor axis. | +| toolMinor | string | toolMinor axis. | +| toolMajor | string | toolMajor axis. | +| orientation | string | Orientation axis.| +| pressure | string | Pressure axis. | +| x | string | X axis. | +| y | string | Y axis. | +| NULL | string | None. | ## AxisRange @@ -333,15 +333,15 @@ Defines the axis range of an input device. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice -| Name | Type | Description | -| ----------------------- | ------------------------- | ---------------- | +| Name | Type | Description | +| ----------------------- | ------------------------- | -------- | | source | [SourceType](#sourcetype) | Input source type of the axis.| -| axis | [AxisType](axistype) | Axis type. | -| max | number | Maximum value of the axis. | -| min | number | Minimum value of the axis. | -| fuzz9+ | number | Fuzzy value of the axis. | -| flat9+ | number | Benchmark value of the axis. | -| resolution9+ | number | Resolution of the axis. | +| axis | [AxisType](#axistype) | Axis type. | +| max | number | Maximum value of the axis. | +| min | number | Minimum value of the axis. | +| fuzz9+ | number | Fuzzy value of the axis. | +| flat9+ | number | Benchmark value of the axis. | +| resolution9+ | number | Resolution of the axis. | ## SourceType @@ -364,10 +364,10 @@ Defines the change type for the hot swap event of an input device. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice -| Name | Type| Description | -| ------ | -------- | ------------------ | -| add | string | An input device is inserted.| -| remove | string | An input device is removed.| +| Name | Type | Description | +| ------ | ------ | --------- | +| add | string | An input device is inserted.| +| remove | string | An input device is removed.| ## KeyboardType9+ @@ -375,11 +375,11 @@ Enumerates the keyboard types. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice -| Name | Type| Value | Description | -| ------------------- | -------- | ---- | ------------------ | -| NONE | number | 0 | Keyboard without keys | -| UNKNOWN | number | 1 | Keyboard with unknown keys| -| ALPHABETIC_KEYBOARD | number | 2 | Full keyboard | -| DIGITAL_KEYBOARD | number | 3 | Keypad | -| HANDWRITING_PEN | number | 4 | Stylus | -| REMOTE_CONTROL | number | 5 | Remote control | +| Name | Type | Value | Description | +| ------------------- | ------ | ---- | --------- | +| NONE | number | 0 | Keyboard without keys. | +| UNKNOWN | number | 1 | Keyboard with unknown keys.| +| ALPHABETIC_KEYBOARD | number | 2 | Full keyboard. | +| DIGITAL_KEYBOARD | number | 3 | Keypad. | +| HANDWRITING_PEN | number | 4 | Stylus. | +| REMOTE_CONTROL | number | 5 | Remote control. | diff --git a/en/application-dev/reference/apis/js-apis-inputevent.md b/en/application-dev/reference/apis/js-apis-inputevent.md new file mode 100644 index 0000000000000000000000000000000000000000..5718f96c2c75a8950af27d7de8e9ad40866d4198 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inputevent.md @@ -0,0 +1,22 @@ +# Input Event + +> **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 InputEvent from '@ohos.multimodalInput.inputEvent'; +``` + +**System capability**: SystemCapability.MultimodalInput.Input.Core + +**Parameters** + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| id | number | Yes| No| Unique event ID generated by the server.| +| deviceId | number | Yes| No| ID of the device that reports the input event.| +| actionTime | number | Yes| No| Time when the event is reported.| +| screenId | number | Yes| No| ID of the target screen.| +| windowId | number | Yes| No| ID of the target window.| diff --git a/en/application-dev/reference/apis/js-apis-inputeventclient.md b/en/application-dev/reference/apis/js-apis-inputeventclient.md index ed3942bb5920474b06ae829521a77bf483d1cac0..be8c4ad17b0963d9761194eb009580ef37347e31 100644 --- a/en/application-dev/reference/apis/js-apis-inputeventclient.md +++ b/en/application-dev/reference/apis/js-apis-inputeventclient.md @@ -1,17 +1,17 @@ -# Input Event Client +# Key Injection -> ![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. +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> - The APIs of this module are system APIs and cannot be called by third-party applications. +> The APIs of this module are system APIs and cannot be called by third-party applications. ## Modules to Import -``` +```js import inputEventClient from '@ohos.multimodalInput.inputEventClient'; ``` @@ -20,38 +20,40 @@ import inputEventClient from '@ohos.multimodalInput.inputEventClient'; injectEvent({KeyEvent: KeyEvent}): void -Injects a key. +Injects a key event. **System capability**: SystemCapability.MultimodalInput.Input.InputSimulator **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| KeyEvent | [KeyEvent](#keyevent) | Yes| Information about the key to inject.| +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | --------- | +| KeyEvent | [KeyEvent](#keyevent) | Yes | Information about the key event to inject.| **Example** -``` +```js let keyEvent = { isPressed: true, keyCode: 2, keyDownDuration: 0, isIntercepted: false } -res = inputEventClient.injectEvent({KeyEvent: keyEvent}); +let res = inputEventClient.injectEvent({KeyEvent: keyEvent}); ``` ## KeyEvent -Defines the information about the key to inject. +Defines the information about the key event to inject. **System capability**: SystemCapability.MultimodalInput.Input.InputSimulator -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| isPressed | boolean | Yes| Whether the key is pressed.| -| keyCode | Number | Yes| Key code.| -| keyDownDuration | boolean | Yes| Duration for which the key is pressed.| -| isIntercepted | Number | Yes| Whether the key can be intercepted.| +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------- | ------- | ---- | --------- | +| isPressed | boolean | Yes | Whether the key is pressed. | +| keyCode | Number | Yes | Key code. | +| keyDownDuration | boolean | Yes | Duration within which the key is pressed. | +| isIntercepted | Number | Yes | Whether the key can be intercepted.| diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md index a89590f552dd1a55408fd2743bffc9cde1f73e14..c61ca55fd32ff103763e4271392c0e23c83deda7 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -1,6 +1,6 @@ # Input Method Framework -> ![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. +> **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. > @@ -48,9 +48,9 @@ Obtains an [InputMethodController](#InputMethodController) instance. **Example** -``` -var InputMethodController = inputMethod.getInputMethodController(); -``` + ```js + var InputMethodController = inputMethod.getInputMethodController(); + ``` ## inputMethod.getInputMethodSetting8+ @@ -140,18 +140,18 @@ Obtains the list of installed input methods. This API uses an asynchronous callb **Example** -```js - InputMethodSetting.listInputMethod((properties)=>{ - for (var i = 0;i < properties.length; i++) { - var property = properties[i]; - console.info(property.packageName + "/" + property.methodId); - } -}); -``` + ```js + InputMethodSetting.listInputMethod((properties)=>{ + for (var i = 0;i < properties.length; i++) { + var property = properties[i]; + console.info(property.packageName + "/" + property.methodId); + } + }); + ``` ### listInputMethod -listInputMethod(): Array<InputMethodProperty> +listInputMethod(): Promise<Array<InputMethodProperty>> Obtains the list of installed input methods. This API uses an asynchronous callback to return the result. diff --git a/en/application-dev/reference/apis/js-apis-inputmonitor.md b/en/application-dev/reference/apis/js-apis-inputmonitor.md index 6feb477120e3c128c26086b199faab2e5a5caede..6bbd043fd8eefaf4809c123e0b3fb465b9d59722 100644 --- a/en/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/en/application-dev/reference/apis/js-apis-inputmonitor.md @@ -3,6 +3,7 @@ > **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. @@ -29,7 +30,8 @@ Enables listening for global touch events. **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor - **Parameters** +**Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | ------------------------------- | | type | string | Yes | Type of the input event to listen for. The value is **touch**.| @@ -52,7 +54,7 @@ Enables listening for global mouse events. **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor - **Parameters** +**Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------------- | @@ -73,13 +75,14 @@ inputMonitor.off("mouse", (event) => { off(type: "touch", receiver?:TouchEventReceiver):void -Enables listening for global touch events. +Stops listening for global touch events. **Required permissions**: ohos.permission.INPUT_MONITORING **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor - **Parameters** +**Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | ------------------------------- | | type | string | Yes | Type of the input event to listen for. The value is **touch**.| @@ -99,7 +102,7 @@ Stops listening for global mouse events. **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor - **Parameters** +**Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------------- | @@ -116,7 +119,7 @@ inputMonitor.off("mouse"); ## TouchEventReceiver -Represents the class of the callback used to return the touch event. The value **true** indicates that the touch event has been consumed, and the value **false** indicates the opposite. +This class provides the callback of touch events. ### (touchEvent: TouchEvent): Boolean @@ -125,12 +128,14 @@ Represents the callback used to return the touch event. You need to define the n **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor - **Parameters** +**Parameters** + | Name | Type | Mandatory | Description | | ---------- | ---------------------------------------- | ---- | ---------------------------------------- | | touchEvent | [TouchEvent](../arkui-js/js-components-common-events.md) | Yes | Callback used to return the touch event.| - **Return value** +**Return value** + | Type | Description | | ------- | -------------------------------------- | | Boolean | Result indicating whether the touch event has been consumed by the input monitor. The value **true** indicates that the touch event has been consumed, and the value **false** indicates the opposite.| diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index ef18b367bd83082946103da35aba0cf6684e8e87..2ae9a62bcd2d4a436cfdef61c31383ed929b09b6 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -136,7 +136,7 @@ Represents the locale options. | Name | Type | Readable | Writable | Description | | --------------- | ------- | ---- | ---- | ---------------------------------------- | -| calendar | string | Yes | Yes | Calendar for the locale. The calue can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| +| calendar | string | Yes | Yes | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| | collation | string | Yes | Yes | Collation rule. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **emoji**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**,**search**, **searchjl**, **standard**, **stroke**, **trad**, **unihan**, **zhuyin**.| | hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| | numberingSystem | string | Yes | Yes | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| diff --git a/en/application-dev/reference/apis/js-apis-keycode.md b/en/application-dev/reference/apis/js-apis-keycode.md new file mode 100644 index 0000000000000000000000000000000000000000..5bf402c3d736c674c767a915147f2a43c850c23b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-keycode.md @@ -0,0 +1,347 @@ +# Keycode + +Provides keycodes for a key 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 + +```js +import {KeyCode} from '@ohos.multimodalInput.keyCode' +``` + +**System capability**: SystemCapability.MultimodalInput.Input.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| KEYCODE_FN | number | Yes| No| Function (Fn) key| +| KEYCODE_UNKNOWN | number | Yes| No| Unknown key| +| KEYCODE_HOME | number | Yes| No| Home key | +| KEYCODE_BACK | number | Yes| No| Back key| +| KEYCODE_MEDIA_PLAY_PAUSE | number | Yes| No| Play/Pause key| +| KEYCODE_MEDIA_STOP | number | Yes| No| Stop key| +| KEYCODE_MEDIA_NEXT | number | Yes| No| Next key| +| KEYCODE_MEDIA_PREVIOUS | number | Yes| No| Previous key| +| KEYCODE_MEDIA_REWIND | number | Yes| No| Rewind key| +| KEYCODE_MEDIA_FAST_FORWARD | number | Yes| No| Fast Forward key| +| KEYCODE_VOLUME_UP | number | Yes| No| Volume Up key| +| KEYCODE_VOLUME_DOWN | number | Yes| No| Volume Down key| +| KEYCODE_POWER | number | Yes| No| Power key| +| KEYCODE_CAMERA | number | Yes| No| Camera key| +| KEYCODE_VOLUME_MUTE | number | Yes| No| Speaker Mute key| +| KEYCODE_MUTE | number | Yes| No| Mute key| +| KEYCODE_BRIGHTNESS_UP | number | Yes| No| Brightness Up key| +| KEYCODE_BRIGHTNESS_DOWN | number | Yes| No| Brightness Down key| +| KEYCODE_0 | number | Yes| No| Key 0| +| KEYCODE_1 | number | Yes| No| Key 1| +| KEYCODE_2 | number | Yes| No| Key 2| +| KEYCODE_3 | number | Yes| No| Key 3| +| KEYCODE_4 | number | Yes| No| Key 4| +| KEYCODE_5 | number | Yes| No| Key 5| +| KEYCODE_6 | number | Yes| No| Key 6| +| KEYCODE_7 | number | Yes| No| Key 7| +| KEYCODE_8 | number | Yes| No| Key 8| +| KEYCODE_9 | number | Yes| No| Key 9| +| KEYCODE_STAR | number | Yes| No| Key *| +| KEYCODE_POUND | number | Yes| No| Key #| +| KEYCODE_DPAD_UP | number | Yes| No| Up key on D-pad| +| KEYCODE_DPAD_DOWN | number | Yes| No| Down key on D-pad| +| KEYCODE_DPAD_LEFT | number | Yes| No| Left key on D-pad| +| KEYCODE_DPAD_RIGHT | number | Yes| No| Right key on D-pad| +| KEYCODE_DPAD_CENTER | number | Yes| No| Center key on D-pad| +| KEYCODE_A | number | Yes| No| Key A| +| KEYCODE_B | number | Yes| No| Key B| +| KEYCODE_C | number | Yes| No| Key C| +| KEYCODE_D | number | Yes| No| Key D| +| KEYCODE_E | number | Yes| No| Key E| +| KEYCODE_F | number | Yes| No| Key F| +| KEYCODE_G | number | Yes| No| Key G| +| KEYCODE_H | number | Yes| No| Key H| +| KEYCODE_I | number | Yes| No| Key I| +| KEYCODE_J | number | Yes| No| Key J| +| KEYCODE_K | number | Yes| No| Key K| +| KEYCODE_L | number | Yes| No| Key L| +| KEYCODE_M | number | Yes| No| Key M| +| KEYCODE_N | number | Yes| No| Key N| +| KEYCODE_O | number | Yes| No| Key O| +| KEYCODE_P | number | Yes| No| Key P| +| KEYCODE_Q | number | Yes| No| Key Q| +| KEYCODE_R | number | Yes| No| Key R| +| KEYCODE_S | number | Yes| No| Key S| +| KEYCODE_T | number | Yes| No| Key T| +| KEYCODE_U | number | Yes| No| Key U| +| KEYCODE_V | number | Yes| No| Key V| +| KEYCODE_W | number | Yes| No| Key W| +| KEYCODE_X | number | Yes| No| Key X| +| KEYCODE_Y | number | Yes| No| Key Y| +| KEYCODE_Z | number | Yes| No| Key Z| +| KEYCODE_COMMA | number | Yes| No| Key ,| +| KEYCODE_PERIOD | number | Yes| No| Key .| +| KEYCODE_ALT_LEFT | number | Yes| No| Alt+Left key| +| KEYCODE_ALT_RIGHT | number | Yes| No| Alt+Right key| +| KEYCODE_SHIFT_LEFT | number | Yes| No| Shift+Left key| +| KEYCODE_SHIFT_RIGHT | number | Yes| No| Shift+Right key| +| KEYCODE_TAB | number | Yes| No| Tab key| +| KEYCODE_SPACE | number | Yes| No| Space key| +| KEYCODE_SYM | number | Yes| No| Symbol key| +| KEYCODE_EXPLORER | number | Yes| No| Explorer key, which is used to start the explorer application| +| KEYCODE_ENVELOPE | number | Yes| No| Email key, which is used to start the email application| +| KEYCODE_ENTER | number | Yes| No| Enter key| +| KEYCODE_DEL | number | Yes| No| Delete key| +| KEYCODE_GRAVE | number | Yes| No| Key `| +| KEYCODE_MINUS | number | Yes| No| Key -| +| KEYCODE_EQUALS | number | Yes| No| Key =| +| KEYCODE_LEFT_BRACKET | number | Yes| No| Key [| +| KEYCODE_RIGHT_BRACKET | number | Yes| No| Key ]| +| KEYCODE_BACKSLASH | number | Yes| No| Key \| +| KEYCODE_SEMICOLON | number | Yes| No| Key ;| +| KEYCODE_APOSTROPHE | number | Yes| No| Key ' | +| KEYCODE_SLASH | number | Yes| No| Key /| +| KEYCODE_AT | number | Yes| No| Key @| +| KEYCODE_PLUS | number | Yes| No| Key +| +| KEYCODE_MENU | number | Yes| No| Menu key| +| KEYCODE_PAGE_UP | number | Yes| No| Page Up key| +| KEYCODE_PAGE_DOWN | number | Yes| No| Page Down key| +| KEYCODE_ESCAPE | number | Yes| No| ESC key| +| KEYCODE_FORWARD_DEL | number | Yes| No| Delete key| +| KEYCODE_CTRL_LEFT | number | Yes| No| Control+Left | +| KEYCODE_CTRL_RIGHT | number | Yes| No| Control+Right | +| KEYCODE_CAPS_LOCK | number | Yes| No| Caps Lock key| +| KEYCODE_SCROLL_LOCK | number | Yes| No| Scroll Lock key| +| KEYCODE_META_LEFT | number | Yes| No| Left Meta key| +| KEYCODE_META_RIGHT | number | Yes| No| Right Meta key| +| KEYCODE_FUNCTION | number | Yes| No| Function key| +| KEYCODE_SYSRQ | number | Yes| No| System Request/Print Screen key| +| KEYCODE_BREAK | number | Yes| No| Break/Pause key| +| KEYCODE_MOVE_HOME | number | Yes| No| Move to Home key| +| KEYCODE_MOVE_END | number | Yes| No| Move to End key| +| KEYCODE_INSERT | number | Yes| No| Insert key| +| KEYCODE_FORWARD | number | Yes| No| Delete key | +| KEYCODE_MEDIA_PLAY | number | Yes| No| Play key| +| KEYCODE_MEDIA_PAUSE | number | Yes| No| Pause key| +| KEYCODE_MEDIA_CLOSE | number | Yes| No| Close key| +| KEYCODE_MEDIA_EJECT | number | Yes| No| Eject key| +| KEYCODE_MEDIA_RECORD | number | Yes| No| Record key| +| KEYCODE_F1 | number | Yes| No| F1 key| +| KEYCODE_F2 | number | Yes| No| F2 key| +| KEYCODE_F3 | number | Yes| No| F3 key| +| KEYCODE_F4 | number | Yes| No| F4 key| +| KEYCODE_F5 | number | Yes| No| F5 key| +| KEYCODE_F6 | number | Yes| No| F6 key| +| KEYCODE_F7 | number | Yes| No| F7 key| +| KEYCODE_F8 | number | Yes| No| F8 key| +| KEYCODE_F9 | number | Yes| No| F9 key| +| KEYCODE_F10 | number | Yes| No| F10 key| +| KEYCODE_F11 | number | Yes| No| F11 key| +| KEYCODE_F12 | number | Yes| No| F12 key| +| KEYCODE_NUM_LOCK | number | Yes| No| Number Lock key| +| KEYCODE_NUMPAD_0 | number | Yes| No| Key 0 on numeric keypad| +| KEYCODE_NUMPAD_1 | number | Yes| No| Key 1 on numeric keypad| +| KEYCODE_NUMPAD_2 | number | Yes| No| Key 2 on numeric keypad| +| KEYCODE_NUMPAD_3 | number | Yes| No| Key 3 on numeric keypad| +| KEYCODE_NUMPAD_4 | number | Yes| No| Key 4 on numeric keypad| +| KEYCODE_NUMPAD_5 | number | Yes| No| Key 5 on numeric keypad| +| KEYCODE_NUMPAD_6 | number | Yes| No| Key 6 on numeric keypad| +| KEYCODE_NUMPAD_7 | number | Yes| No| Key 7 on numeric keypad| +| KEYCODE_NUMPAD_8 | number | Yes| No| Key 8 on numeric keypad| +| KEYCODE_NUMPAD_9 | number | Yes| No| Key 9 on numeric keypad| +| KEYCODE_NUMPAD_DIVIDE | number | Yes| No| Key / on numeric keypad| +| KEYCODE_NUMPAD_MULTIPLY | number | Yes| No| Key * on numeric keypad| +| KEYCODE_NUMPAD_SUBTRACT | number | Yes| No| Key - on numeric keypad| +| KEYCODE_NUMPAD_ADD | number | Yes| No| Key + on numeric keypad| +| KEYCODE_NUMPAD_DOT | number | Yes| No| Key . on numeric keypad| +| KEYCODE_NUMPAD_COMMA | number | Yes| No| Key , on numeric keypad| +| KEYCODE_NUMPAD_ENTER | number | Yes| No| Enter key on numeric keypad| +| KEYCODE_NUMPAD_EQUALS | number | Yes| No| Key = on numeric keypad| +| KEYCODE_NUMPAD_LEFT_PAREN | number | Yes| No| Key ( on numeric keypad| +| KEYCODE_NUMPAD_RIGHT_PAREN | number | Yes| No| Key ) on numeric keypad| +| KEYCODE_VIRTUAL_MULTITASK | number | Yes| No| Multi-task key| +| KEYCODE_SLEEP | number | Yes| No| Sleep key| +| KEYCODE_ZENKAKU_HANKAKU | number | Yes| No| Zenkaku/Hankaku key| +| KEYCODE_102ND | number | Yes| No| 102nd key| +| KEYCODE_RO | number | Yes| No| Ro key| +| KEYCODE_KATAKANA | number | Yes| No| Katakana key| +| KEYCODE_HIRAGANA | number | Yes| No| Hiragana key| +| KEYCODE_HENKAN | number | Yes| No| Henkan key| +| KEYCODE_KATAKANA_HIRAGANA | number | Yes| No| Katakana/Hiragana key| +| KEYCODE_MUHENKAN | number | Yes| No| Muhenkan key| +| KEYCODE_LINEFEED | number | Yes| No| Linefeed key| +| KEYCODE_MACRO | number | Yes| No| Macro key| +| KEYCODE_NUMPAD_PLUSMINUS | number | Yes| No| Plus/Minus key on the numeric keypad| +| KEYCODE_SCALE | number | Yes| No| Scale key| +| KEYCODE_HANGUEL | number | Yes| No| Hanguel key| +| KEYCODE_HANJA | number | Yes| No| Hanja key| +| KEYCODE_YEN | number | Yes| No| Yen key| +| KEYCODE_STOP | number | Yes| No| Stop key| +| KEYCODE_AGAIN | number | Yes| No| Again key| +| KEYCODE_PROPS | number | Yes| No| Props key| +| KEYCODE_UNDO | number | Yes| No| Undo key| +| KEYCODE_COPY | number | Yes| No| Copy key| +| KEYCODE_OPEN | number | Yes| No| Open key| +| KEYCODE_PASTE | number | Yes| No| Paste key| +| KEYCODE_FIND | number | Yes| No| Find key| +| KEYCODE_CUT | number | Yes| No| Cut key| +| KEYCODE_HELP | number | Yes| No| Help key| +| KEYCODE_CALC | number | Yes| No| Calc key, which is used to start the calculator application| +| KEYCODE_FILE | number | Yes| No| File key| +| KEYCODE_BOOKMARKS | number | Yes| No| Bookmarks key| +| KEYCODE_NEXT | number | Yes| No| Next key| +| KEYCODE_PLAYPAUSE | number | Yes| No| Play/Pause key| +| KEYCODE_PREVIOUS | number | Yes| No| Previous key| +| KEYCODE_STOPCD | number | Yes| No| Stop CD key| +| KEYCODE_CONFIG | number | Yes| No| Config key| +| KEYCODE_REFRESH | number | Yes| No| Refresh key| +| KEYCODE_EXIT | number | Yes| No| Exit key| +| KEYCODE_EDIT | number | Yes| No| Edit key| +| KEYCODE_SCROLLUP | number | Yes| No| Scroll Up key| +| KEYCODE_SCROLLDOWN | number | Yes| No| Scroll Down key| +| KEYCODE_NEW | number | Yes| No| New key| +| KEYCODE_REDO | number | Yes| No| Redo key| +| KEYCODE_CLOSE | number | Yes| No| Close key| +| KEYCODE_PLAY | number | Yes| No| Play key| +| KEYCODE_BASSBOOST | number | Yes| No| Bass Boost key| +| KEYCODE_PRINT | number | Yes| No| Print key| +| KEYCODE_CHAT | number | Yes| No| Chat key| +| KEYCODE_FINANCE | number | Yes| No| Finance key| +| KEYCODE_CANCEL | number | Yes| No| Cancel key| +| KEYCODE_KBDILLUM_TOGGLE | number | Yes| No| Keyboard Illumination Toggle key| +| KEYCODE_KBDILLUM_DOWN | number | Yes| No| Keyboard Illumination Up key| +| KEYCODE_KBDILLUM_UP | number | Yes| No| Keyboard Illumination Down key| +| KEYCODE_SEND | number | Yes| No| Send key| +| KEYCODE_REPLY | number | Yes| No| Reply key| +| KEYCODE_FORWARDMAIL | number | Yes| No| Forward Mail key| +| KEYCODE_SAVE | number | Yes| No| Save key| +| KEYCODE_DOCUMENTS | number | Yes| No| Documents key| +| KEYCODE_VIDEO_NEXT | number | Yes| No| Next Video key| +| KEYCODE_VIDEO_PREV | number | Yes| No| Previous Video key| +| KEYCODE_BRIGHTNESS_CYCLE | number | Yes| No| Brightness Cycle key| +| KEYCODE_BRIGHTNESS_ZERO | number | Yes| No| Brightness Zero key| +| KEYCODE_DISPLAY_OFF | number | Yes| No| Display Off Key| +| KEYCODE_BTN_MISC | number | Yes| No| Misc Button key| +| KEYCODE_GOTO | number | Yes| No| Goto key| +| KEYCODE_INFO | number | Yes| No| Info key| +| KEYCODE_PROGRAM | number | Yes| No| Program key| +| KEYCODE_PVR | number | Yes| No| PVR key| +| KEYCODE_SUBTITLE | number | Yes| No| Subtitle key| +| KEYCODE_FULL_SCREEN | number | Yes| No| Full Screen key| +| KEYCODE_KEYBOARD | number | Yes| No| Keyboard| +| KEYCODE_ASPECT_RATIO | number | Yes| No| Aspect Ratio key| +| KEYCODE_PC | number | Yes| No| Port Control key| +| KEYCODE_TV | number | Yes| No| TV key| +| KEYCODE_TV2 | number | Yes| No| TV key 2| +| KEYCODE_VCR | number | Yes| No| VCR key| +| KEYCODE_VCR2 | number | Yes| No| VCR key 2| +| KEYCODE_SAT | number | Yes| No| SAT key| +| KEYCODE_CD | number | Yes| No| CD key| +| KEYCODE_TAPE | number | Yes| No| Tape key| +| KEYCODE_TUNER | number | Yes| No| Tuner key| +| KEYCODE_PLAYER | number | Yes| No| Player key| +| KEYCODE_DVD | number | Yes| No| DVD key| +| KEYCODE_AUDIO | number | Yes| No| Audio key| +| KEYCODE_VIDEO | number | Yes| No| Video key| +| KEYCODE_MEMO | number | Yes| No| Memo key| +| KEYCODE_CALENDAR | number | Yes| No| Calendar key| +| KEYCODE_RED | number | Yes| No| Red indicator| +| KEYCODE_GREEN | number | Yes| No| Green indicator| +| KEYCODE_YELLOW | number | Yes| No| Yellow indicator| +| KEYCODE_BLUE | number | Yes| No| Blue indicator| +| KEYCODE_CHANNELUP | number | Yes| No| Channel Up key| +| KEYCODE_CHANNELDOWN | number | Yes| No| Channel Down key| +| KEYCODE_LAST | number | Yes| No| Last key| +| KEYCODE_RESTART | number | Yes| No| Restart key| +| KEYCODE_SLOW | number | Yes| No| Slow key| +| KEYCODE_SHUFFLE | number | Yes| No| Shuffle key| +| KEYCODE_VIDEOPHONE | number | Yes| No| Videophone key| +| KEYCODE_GAMES | number | Yes| No| Games key| +| KEYCODE_ZOOMIN | number | Yes| No| Zoom-in key| +| KEYCODE_ZOOMOUT | number | Yes| No| Zoom-out key| +| KEYCODE_ZOOMRESET | number | Yes| No| Zoom Reset key| +| KEYCODE_WORDPROCESSOR | number | Yes| No| Word Processor key| +| KEYCODE_EDITOR | number | Yes| No| Editor key| +| KEYCODE_SPREADSHEET | number | Yes| No| Spreadsheet key| +| KEYCODE_GRAPHICSEDITOR | number | Yes| No| Graphics Editor key| +| KEYCODE_PRESENTATION | number | Yes| No| Presentation key| +| KEYCODE_DATABASE | number | Yes| No| Database key| +| KEYCODE_NEWS | number | Yes| No| News key| +| KEYCODE_VOICEMAIL | number | Yes| No| Voicemail key| +| KEYCODE_ADDRESSBOOK | number | Yes| No| Addressbook key| +| KEYCODE_MESSENGER | number | Yes| No| Messenger key| +| KEYCODE_BRIGHTNESS_TOGGLE | number | Yes| No| Brightness Toggle key| +| KEYCODE_SPELLCHECK | number | Yes| No| Spell Check key| +| KEYCODE_COFFEE | number | Yes| No| Coffee key, which is used to launch screen lock or screen saver| +| KEYCODE_MEDIA_REPEAT | number | Yes| No| Media Repeat key| +| KEYCODE_IMAGES | number | Yes| No| Images key| +| KEYCODE_BUTTONCONFIG | number | Yes| No| Button Configuration key| +| KEYCODE_TASKMANAGER | number | Yes| No| Task Manager key| +| KEYCODE_JOURNAL | number | Yes| No| Log key| +| KEYCODE_CONTROLPANEL | number | Yes| No| Control Panel key| +| KEYCODE_APPSELECT | number | Yes| No| App Select key| +| KEYCODE_SCREENSAVER | number | Yes| No| Screen Saver key| +| KEYCODE_ASSISTANT | number | Yes| No| Assistant key| +| KEYCODE_KBD_LAYOUT_NEXT | number | Yes| No| Next Keyboard Layout key| +| KEYCODE_BRIGHTNESS_MIN | number | Yes| No| Min Brightness key| +| KEYCODE_BRIGHTNESS_MAX | number | Yes| No| Max Brightness key| +| KEYCODE_KBDINPUTASSIST_PREV | number | Yes| No| Keyboard Input-assisted Previous key| +| KEYCODE_KBDINPUTASSIST_NEXT | number | Yes| No| Keyboard Input-assisted Next key| +| KEYCODE_KBDINPUTASSIST_PREVGROUP | number | Yes| No| Keyboard Input-assisted Previous Group key| +| KEYCODE_KBDINPUTASSIST_NEXTGROUP | number | Yes| No| Keyboard Input-assisted Next Group key| +| KEYCODE_KBDINPUTASSIST_ACCEPT | number | Yes| No| Keyboard Input-assisted Accept key| +| KEYCODE_KBDINPUTASSIST_CANCEL | number | Yes| No| Keyboard Input-assisted Cancel key| +| KEYCODE_FRONT | number | Yes| No| Front key, which is used to launch the windshield defogger| +| KEYCODE_SETUP | number | Yes| No| Setup key| +| KEYCODE_WAKEUP | number | Yes| No| Wakeup key| +| KEYCODE_SENDFILE | number | Yes| No| Send File key| +| KEYCODE_DELETEFILE | number | Yes| No| Delete File key| +| KEYCODE_XFER | number | Yes| No| XFER key, which is used to start file transfer| +| KEYCODE_PROG1 | number | Yes| No| Program key 1| +| KEYCODE_PROG2 | number | Yes| No| Program key 2| +| KEYCODE_MSDOS | number | Yes| No| MS-DOS key| +| KEYCODE_SCREENLOCK | number | Yes| No| Screen Lock key| +| KEYCODE_DIRECTION_ROTATE_DISPLAY | number | Yes| No| Directional Rotation Display key| +| KEYCODE_CYCLEWINDOWS | number | Yes| No| Windows Cycle key| +| KEYCODE_COMPUTER | number | Yes| No| Computer key| +| KEYCODE_EJECTCLOSECD | number | Yes| No| Eject CD key| +| KEYCODE_ISO | number | Yes| No| ISO key| +| KEYCODE_MOVE | number | Yes| No| Move key| +| KEYCODE_F13 | number | Yes| No| F13 key| +| KEYCODE_F14 | number | Yes| No| F14 key| +| KEYCODE_F15 | number | Yes| No| F15 key| +| KEYCODE_F16 | number | Yes| No| F16 key| +| KEYCODE_F17 | number | Yes| No| F17 key| +| KEYCODE_F18 | number | Yes| No| F18 key| +| KEYCODE_F19 | number | Yes| No| F19 key| +| KEYCODE_F20 | number | Yes| No| F20 key| +| KEYCODE_F21 | number | Yes| No| F21 key| +| KEYCODE_F22 | number | Yes| No| F22 key| +| KEYCODE_F23 | number | Yes| No| F23 key| +| KEYCODE_F24 | number | Yes| No| F24 key| +| KEYCODE_PROG3 | number | Yes| No| Program key 3| +| KEYCODE_PROG4 | number | Yes| No| Program key 4| +| KEYCODE_DASHBOARD | number | Yes| No| Dashboard| +| KEYCODE_SUSPEND | number | Yes| No| Suspend key| +| KEYCODE_HP | number | Yes| No| HP key| +| KEYCODE_SOUND | number | Yes| No| Sound key| +| KEYCODE_QUESTION | number | Yes| No| Question key| +| KEYCODE_CONNECT | number | Yes| No| Connect key| +| KEYCODE_SPORT | number | Yes| No| Sport key| +| KEYCODE_SHOP | number | Yes| No| Shop key| +| KEYCODE_ALTERASE | number | Yes| No| Alternate key| +| KEYCODE_SWITCHVIDEOMODE | number | Yes| No| Switch Video Mode key (monitor, LCD, and TV, etc.)| +| KEYCODE_BATTERY | number | Yes| No| Battery key| +| KEYCODE_BLUETOOTH | number | Yes| No| Bluetooth key| +| KEYCODE_WLAN | number | Yes| No| WLAN key| +| KEYCODE_UWB | number | Yes| No| Ultra-wideband key| +| KEYCODE_WWAN_WIMAX | number | Yes| No| WWAN WiMAX key| +| KEYCODE_RFKILL | number | Yes| No| RF Kill key| +| KEYCODE_CHANNEL | number | Yes| No| Channel key| +| KEYCODE_BTN_0 | number | Yes| No| Key 0| +| KEYCODE_BTN_1 | number | Yes| No| Button 1| +| KEYCODE_BTN_2 | number | Yes| No| Button 2| +| KEYCODE_BTN_3 | number | Yes| No| Button 3| +| KEYCODE_BTN_4 | number | Yes| No| Button 4| +| KEYCODE_BTN_5 | number | Yes| No| Button 5| +| KEYCODE_BTN_6 | number | Yes| No| Button 6| +| KEYCODE_BTN_7 | number | Yes| No| Button 7| +| KEYCODE_BTN_8 | number | Yes| No| Button 8| +| KEYCODE_BTN_9 | number | Yes| No| Button 9| diff --git a/en/application-dev/reference/apis/js-apis-keyevent.md b/en/application-dev/reference/apis/js-apis-keyevent.md new file mode 100644 index 0000000000000000000000000000000000000000..085bee426f36b96e2538ab4ad8f13cf5086b5b9c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-keyevent.md @@ -0,0 +1,51 @@ +# Key Event + +Represents key events reported by an input 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 + +```js +import {Action,Key,KeyEvent} from '@ohos.multimodalInput.keyEvent'; +``` + +## Action + +**System capability**: SystemCapability.MultimodalInput.Input.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| CANCEL | number | Yes| No| Cancellation of a key action.| +| DOWN | number | Yes| No| Pressing of a key.| +| UP | number | Yes| No| Release of a key.| + +## Key + +**System capability**: SystemCapability.MultimodalInput.Input.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| code | KeyCode | Yes| No| Keycode.| +| pressedTime | number | Yes| No| Time when the key is pressed.| +| deviceId | number | Yes| No| Device to which the key belongs.| + +## KeyEvent + +**System capability**: SystemCapability.MultimodalInput.Input.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| action | Action | Yes| No| Key action.| +| key | Key | Yes| No| Key that has changed.| +| unicodeChar | number | Yes| No| Unicode character corresponding to the key.| +| keys | Key[] | Yes| No| List of pressed keys.| +| ctrlKey | boolean | Yes| No| Whether ctrlKey is being pressed.| +| altKey | boolean | Yes| No| Whether altKey is being pressed.| +| shiftKey | boolean | Yes| No| Whether shiftKey is being pressed.| +| logoKey | boolean | Yes| No| Whether logoKey is being pressed.| +| fnKey | boolean | Yes| No| Whether fnKey is being pressed.| +| capsLock | boolean | Yes| No| Whether capsLock is active.| +| numLock | boolean | Yes| No| Whether numLock is active.| +| scrollLock | boolean | Yes| No| Whether scrollLock is active.| diff --git a/en/application-dev/reference/apis/js-apis-lightweightmap.md b/en/application-dev/reference/apis/js-apis-lightweightmap.md index 5273e9290e9be72ee4c4ed9e7aefc412c6805e2a..5ac480761ba58f22e2f120aeaa0aca58faed366d 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightmap.md +++ b/en/application-dev/reference/apis/js-apis-lightweightmap.md @@ -1,27 +1,34 @@ # Nonlinear Container LightWeightMap -> ![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. +**LightWeightMap** stores key-value (KV) pairs. Each key must be unique and have only one value. + +**LightWeightMap** is based on generics and uses a lightweight structure. Keys in the map are searched using hash values, which are stored in an array. + +Compared with **[HashMap](js-apis-hashmap.md)**, which can also store KV pairs, **LightWeightMap** occupies less memory. + +**Recommended use case**: Use LightWeightMap when you need to store and access **KV pairs**. ## Modules to Import ```ts -import LightWeightMap from '@ohos.util.LightWeightMap' +import LightWeightMap from '@ohos.util.LightWeightMap'; ``` -## System Capabilities -SystemCapability.Utils.Lang ## LightWeightMap - ### Attributes +**System capability**: SystemCapability.Utils.Lang + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Number of entries in a lightweight map (called container later).| +| length | number | Yes| No| Number of elements in a lightweight map (called container later).| ### constructor @@ -30,6 +37,8 @@ constructor() A constructor used to create a **LightWeightMap** instance. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -41,7 +50,9 @@ let lightWeightMap = new LightWeightMap(); isEmpty(): boolean -Checks whether this container is empty (contains no entry). +Checks whether this container is empty (contains no element). + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -61,7 +72,9 @@ let result = lightWeightMap.isEmpty(); hasAll(map: LightWeightMap): boolean -Checks whether this container contains all entries of the specified **LightWeightMap** instance. +Checks whether this container contains all elements of the specified **LightWeightMap** instance. + +**System capability**: SystemCapability.Utils.Lang **Parameters** @@ -73,7 +86,7 @@ Checks whether this container contains all entries of the specified **LightWeigh | Type| Description| | -------- | -------- | -| boolean | Returns **true** if all the entries in the specified **LightWeightMap** instance are contained; returns **false** otherwise.| +| boolean | Returns **true** if all the elements in the specified **LightWeightMap** instance are contained; returns **false** otherwise.| **Example** @@ -93,11 +106,13 @@ hasKey(key: K): boolean; Checks whether this container contains the specified key. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key to check.| +| key | K | Yes| Target key.| **Return value** @@ -122,11 +137,13 @@ hasValue(value: V): boolean Checks whether this container contains the specified value. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | Yes| Value to check.| +| value | V | Yes| Target value.| **Return value** @@ -150,11 +167,13 @@ increaseCapacityTo(minimumCapacity: number): void Increases the capacity of this container. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| minimumCapacity | number | Yes| Minimum number of entries to accommodate in this container.| +| minimumCapacity | number | Yes| Minimum number of elements to accommodate in this container.| **Example** @@ -170,11 +189,13 @@ get(key: K): V Obtains the value of the specified key in this container. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key to query.| +| key | K | Yes| Target key.| **Return value** @@ -196,19 +217,21 @@ let result = lightWeightMap.get("sdfs"); getIndexOfKey(key: K): number -Obtains the index of the first occurrence of an entry with the specified key in this container. +Obtains the index of the first occurrence of an element with the specified key in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key of the entry.| +| key | K | Yes| Key of the element.| **Return value** | Type| Description| | -------- | -------- | -| number | Returns the position index if obtained; returns **-1** if the specified entry is not found.| +| number | Returns the position index if obtained; returns **-1** otherwise.| **Example** @@ -224,19 +247,21 @@ let result = lightWeightMap.getIndexOfKey("sdfs"); getIndexOfValue(value: V): number -Obtains the index of the first occurrence of an entry with the specified value in this container. +Obtains the index of the first occurrence of an element with the specified value in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | Yes| Value of the entry.| +| value | V | Yes| Key of the element.| **Return value** | Type| Description| | -------- | -------- | -| number | Returns the position index if obtained; returns **-1** if the specified entry is not found.| +| number | Returns the position index if obtained; returns **-1** otherwise.| **Example** @@ -252,13 +277,15 @@ let result = lightWeightMap.getIndexOfValue(123); getKeyAt(index: number): K -Obtains the key of an entry at the specified position in this container. +Obtains the key of an element at the specified position in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry.| +| index | number | Yes| Position index of the element.| **Return value** @@ -280,13 +307,15 @@ let result = lightWeightMap.getKeyAt(1); setAll(map: LightWeightMap): void -Adds all entries in a **LightWeightMap** instance to this container. +Adds all elements in a **LightWeightMap** instance to this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| map | LightWeightMap | Yes| **LightWeightMap** instance whose entries are to be added to the current container.| +| map | LightWeightMap | Yes| **LightWeightMap** instance whose elements are to be added to the current container.| **Example** @@ -302,20 +331,22 @@ lightWeightMap.setAll(map); ### set set(key: K, value: V): Object -Adds an entry to this container. +Adds an element to this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key of the entry to add.| -| value | V | Yes| Value of the entry to add.| +| key | K | Yes| Key of the target element.| +| value | V | Yes| Value of the target element.| **Return value** | Type| Description| | -------- | -------- | -| Object | Container that contains the new entry.| +| Object | Container that contains the new element.| **Example** @@ -329,19 +360,21 @@ let result = lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); remove(key: K): V -Removes an entry with the specified key from this container. +Removes an element with the specified key from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key of the entry to remove.| +| key | K | Yes| Target key.| **Return value** | Type| Description| | -------- | -------- | -| V | Value of the entry removed.| +| V | Value of the element removed.| **Example** @@ -357,19 +390,21 @@ lightWeightMap.remove("sdfs"); removeAt(index: number): boolean -Removes an entry at the specified position from this container. +Removes an element at the specified position from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry.| +| index | number | Yes| Position index of the element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the entry is removed successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is removed successfully; returns **false** otherwise.| **Example** @@ -385,14 +420,16 @@ let result = lightWeightMap.removeAt(1); setValueAt(index: number, newValue: V): boolean -Sets a value for an entry at the specified position in this container. +Sets a value for an element at the specified position in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry.| -| newValue | V | Yes| Value of the entry to set.| +| index | number | Yes| Position index of the target element.| +| newValue | V | Yes| Value of the target element to set.| **Return value** @@ -414,13 +451,15 @@ lightWeightMap.setValueAt(1, 3546); getValueAt(index: number): V -Obtains the value of an entry at the specified position in this container. +Obtains the value of an element at the specified position in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry.| +| index | number | Yes| Position index of the element.| **Return value** @@ -444,6 +483,8 @@ clear(): void Clears this container and sets its length to **0**. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -460,6 +501,8 @@ keys(): IterableIterator<K> Obtains an iterator that contains all the keys in this container. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -475,7 +518,7 @@ lightWeightMap.set("sdfs", 356); let iter = lightWeightMap.keys(); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value:" + temp); temp = iter.next().value; } ``` @@ -487,6 +530,8 @@ values(): IterableIterator<V> Obtains an iterator that contains all the values in this container. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -502,7 +547,7 @@ lightWeightMap.set("sdfs", 356); let iter = lightWeightMap.values(); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value:" + temp); temp = iter.next().value; } ``` @@ -512,20 +557,22 @@ while(temp != undefined) { forEach(callbackfn: (value?: V, key?: K, map?: LightWeightMap) => void, thisArg?: Object): void -Uses a callback to traverse the entries in this container and obtain their position indexes. +Uses a callback to traverse the elements in this container and obtain their position indexes. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.| +| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | No| Value of the entry that is currently traversed.| -| key | K | No| Key of the entry that is currently traversed.| +| value | V | No| Value of the element that is currently traversed.| +| key | K | No| Key of the element that is currently traversed.| | map | LightWeightMap | No| Instance that invokes the **forEach** method.| **Example** @@ -535,7 +582,7 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("sdfs", 123); lightWeightMap.set("dfsghsf", 357); lightWeightMap.forEach((value, key) => { - console.log(value, key); + console.log("value:" + value, key); }); ``` @@ -544,7 +591,9 @@ lightWeightMap.forEach((value, key) => { entries(): IterableIterator<[K, V]> -Obtains an iterator that contains all the entries in this container. +Obtains an iterator that contains all the elements in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -561,8 +610,8 @@ lightWeightMap.set("sdfs", 356); let iter = lightWeightMap.entries(); let temp = iter.next().value; while(temp != undefined) { - console.log(temp[0]); - console.log(temp[1]); + console.log("key:" + temp[0]); + console.log("value:" + temp[1]); temp = iter.next().value; } ``` @@ -571,13 +620,15 @@ while(temp != undefined) { toString(): String -Concatenates the entries in this container into a string and returns the string. +Concatenates the elements in this container into a string and returns the string. + +**System capability**: SystemCapability.Utils.Lang **Return value** - | Type| Description| - | -------- | -------- | - | String | Returns a string.| +| Type| Description| +| -------- | -------- | +| String | String obtained.| **Example** @@ -594,6 +645,8 @@ Concatenates the entries in this container into a string and returns the string. Obtains an iterator, each item of which is a JavaScript object. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -609,16 +662,16 @@ lightWeightMap.set("sdfs", 356); // Method 1: for (let item of lightWeightMap) { - console.log("key: " + item[0]); - console.log("value: " + item[1]); + console.log("key:" + item[0]); + console.log("value:" + item[1]); } // Method 2: let iter = lightWeightMap[Symbol.iterator](); let temp = iter.next().value; while(temp != undefined) { - console.log(temp[0]); - console.log(temp[1]); + console.log("key:" + temp[0]); + console.log("value:" + temp[1]); temp = iter.next().value; } ``` diff --git a/en/application-dev/reference/apis/js-apis-lightweightset.md b/en/application-dev/reference/apis/js-apis-lightweightset.md index a024852f8c94b4df3d6a81727cffae004cbbd67c..4a900d9f5476216ae7e98a0df9d762119753ad36 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightset.md +++ b/en/application-dev/reference/apis/js-apis-lightweightset.md @@ -1,27 +1,36 @@ # Nonlinear Container LightWeightSet -> ![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. +**LightWeightSet** stores a set of values, each of which must be unique. + +**LightWeightSet** is based on generics and uses a lightweight structure. Its default initial capacity is 8, and it has the capacity doubled in each expansion. + +The values in such a set are searched using hash values, which are stored in an array. + +Compared with **[HashSet](js-apis-hashset.md)**, which can also store values, **LightWeightSet** occupies less memory. + +**Recommended use case**: Use **LightWeightSet** when you need a set that has only unique elements or need to deduplicate a set. ## Modules to Import ```ts -import LightWeightSet from '@ohos.util.LightWeightSet' +import LightWeightSet from '@ohos.util.LightWeightSet'; ``` -## System Capabilities -SystemCapability.Utils.Lang ## LightWeightSet - ### Attributes +**System capability**: SystemCapability.Utils.Lang + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Number of entries in a lightweight set (called container later).| +| length | number | Yes| No| Number of elements in a lightweight set (called container later).| ### constructor @@ -30,6 +39,8 @@ constructor() A constructor used to create a **LightWeightSet** instance. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -41,7 +52,9 @@ let lightWeightSet = new LightWeightSet(); isEmpty(): boolean -Checks whether this container is empty. +Checks whether this container is empty (contains no element). + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -60,19 +73,21 @@ let result = lightWeightSet.isEmpty(); add(obj: T): boolean -Adds an entry to this container. +Adds an element to this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| obj | T | Yes| Entry to add.| +| obj | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the entry is added successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is added successfully; returns **false** otherwise.| **Example** @@ -86,13 +101,15 @@ let result = lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); addAll(set: LightWeightSet<T>): boolean -Adds all entries in a **LightWeightSet** instance to this container. +Adds all elements in a **LightWeightSet** instance to this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| set | LightWeightSet<T> | Yes| **LightWeightSet** instance whose entries are to be added to the current container.| +| set | LightWeightSet<T> | Yes| **LightWeightSet** instance whose elements are to be added to the current container.| **Example** @@ -110,7 +127,9 @@ let result = lightWeightSet.addAll(set); hasAll(set: LightWeightSet<T>): boolean -Checks whether this container contains all entries of the specified **LightWeightSet** instance. +Checks whether this container contains all elements of the specified **LightWeightSet** instance. + +**System capability**: SystemCapability.Utils.Lang **Parameters** @@ -122,7 +141,7 @@ Checks whether this container contains all entries of the specified **LightWeigh | Type| Description| | -------- | -------- | -| boolean | Returns **true** if all the entries in the specified **LightWeightSet** instance are contained; returns **false** otherwise.| +| boolean | Returns **true** if all the elements in the specified **LightWeightSet** instance are contained; returns **false** otherwise.| **Example** @@ -142,11 +161,13 @@ has(key: T): boolean Checks whether this container has the specified key. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key| T | Yes| Key to query.| +| key| T | Yes| Target key.| **Return value** @@ -170,6 +191,8 @@ equal(obj: Object): boolean Checks whether this container contains objects of the same type as the specified **obj**. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| @@ -199,11 +222,13 @@ increaseCapacityTo(minimumCapacity: number): void Increases the capacity of this container. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| minimumCapacity | number | Yes| Minimum number of entries to accommodate in the container.| +| minimumCapacity | number | Yes| Minimum number of elements to accommodate in the container.| **Example** @@ -217,19 +242,21 @@ lightWeightSet.increaseCapacityTo(10); getIndexOf(key: T): number -Obtains the position index of the entry with the specified key in this container. +Obtains the position index of the element with the specified key in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key| T | Yes| Key of the entry to query.| +| key| T | Yes| Key of the target element.| **Return value** | Type| Description| | -------- | -------- | -| number | Position index of the entry.| +| number | Position index of the element.| **Example** @@ -245,19 +272,21 @@ let result = lightWeightSet.getIndexOf("sdfs"); remove(key: T): T -Removes an entry of the specified key from this container. +Removes an element of the specified key from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key| T | Yes| Key of the entry to remove.| +| key| T | Yes| Key of the target element.| **Return value** | Type| Description| | -------- | -------- | -| T | Value of the entry removed.| +| T | Value of the element removed.| **Example** @@ -273,19 +302,21 @@ let result = lightWeightSet.remove("sdfs"); removeAt(index: number): boolean -Removes the entry at the specified position from this container. +Removes the element at the specified position from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry.| +| index | number | Yes| Position index of the element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the entry is removed successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is removed successfully; returns **false** otherwise.| **Example** @@ -301,13 +332,15 @@ let result = lightWeightSet.removeAt(1); getValueAt(index: number): T -Obtains the value of the entry at the specified position in this container. +Obtains the value of the element at the specified position in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry.| +| index | number | Yes| Position index of the element.| **Return value** @@ -331,6 +364,8 @@ clear(): void Clears this container and sets its length to **0**. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -345,7 +380,9 @@ lightWeightSet.clear(); toString(): String -Obtains a string that contains all entries in this container. +Obtains a string that contains all elements in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -369,6 +406,8 @@ toArray(): Array<T> Obtains an array that contains all objects in this container. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -391,6 +430,8 @@ values(): IterableIterator<T> Obtains an iterator that contains all the values in this container. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -416,20 +457,22 @@ while(index < lightWeightSet.length) { forEach(callbackfn: (value?: T, key?: T, set?: LightWeightSet<T>) => void, thisArg?: Object): void -Uses a callback to traverse the entries in this container and obtain their position indexes. +Uses a callback to traverse the elements in this container and obtain their position indexes. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.| +| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | No| Value of the entry that is currently traversed.| -| key| T | No| Key of the entry that is currently traversed (same as **value**).| +| value | T | No| Value of the element that is currently traversed.| +| key| T | No| Key of the element that is currently traversed (same as **value**).| | set | LightWeightSet<T> | No| Instance that invokes the **forEach** method.| **Example** @@ -439,7 +482,7 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("sdfs"); lightWeightSet.add("dfsghsf"); lightWeightSet.forEach((value, key) => { - console.log(value, key); + console.log("value:" + value, key); }); ``` @@ -448,7 +491,9 @@ lightWeightSet.forEach((value, key) => { entries(): IterableIterator<[T, T]> -Obtains an iterator that contains all the entries in this container. +Obtains an iterator that contains all the elements in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -477,6 +522,8 @@ while(index < lightWeightSet.length) { Obtains an iterator, each item of which is a JavaScript object. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -492,14 +539,14 @@ lightWeightSet.add("sdfs"); // Method 1: for (let item of lightWeightSet) { - console.log("value: " + item); + console.log("value:" + item); } // Method 2: let iter = lightWeightSet[Symbol.iterator](); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value:" + temp); temp = iter.next().value; } ``` diff --git a/en/application-dev/reference/apis/js-apis-linkedlist.md b/en/application-dev/reference/apis/js-apis-linkedlist.md index 2827999afc78fe6e9c026ce976a9821e1ce35350..73737f14b6078445e1f67762ca43a86a22804dbe 100644 --- a/en/application-dev/reference/apis/js-apis-linkedlist.md +++ b/en/application-dev/reference/apis/js-apis-linkedlist.md @@ -1,28 +1,35 @@ # Linear Container LinkedList -> ![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. +**LinkedList** is implemented based on the doubly linked list. Each node of the doubly linked list has references pointing to the previous element and the next element. When querying an element, the system traverses the list from the beginning or end. **LinkedList** offers efficient insertion and removal operations but supports low query efficiency. **LinkedList** allows null elements. + +Unlike **[List](js-apis-list.md)**, which is a singly linked list, **LinkedList** is a doubly linked list that supports insertion and removal at both ends. + +**LinkedList** is less efficient in data access than **[ArrayList](js-apis-arraylist.md)**. + +**Recommended use case**: Use **LinkedList** for frequent insertion and removal operations. ## Modules to Import ```ts -import LinkedList from '@ohos.util.LinkedList' +import LinkedList from '@ohos.util.LinkedList'; ``` -## System Capability -SystemCapability.Utils.Lang ## LinkedList - ### Attributes +**System capability**: SystemCapability.Utils.Lang + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Number of entries in a linked list (called container later).| +| length | number | Yes| No| Number of elements in a linked list (called container later).| ### constructor @@ -31,6 +38,8 @@ constructor() A constructor used to create a **LinkedList** instance. +**System capability**: SystemCapability.Utils.Lang + **Example** @@ -43,19 +52,21 @@ let linkedList = new LinkedList(); add(element: T): boolean -Adds an entry at the end of this container. +Adds an element at the end of this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to add.| +| element | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the entry is added successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is added successfully; returns **false** otherwise.| **Example** @@ -73,13 +84,15 @@ let result3 = linkedList.add(false); addFirst(element: T): void -Adds an entry at the top of this container. +Adds an element at the top of this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to add.| +| element | T | Yes| Target element.| **Example** @@ -97,14 +110,16 @@ linkedList.addFirst(false); insert(index: number, element: T): void -Inserts an entry at the specified position in this container. +Inserts an element at the specified position in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to insert.| -| index | number | Yes| Index of the position where the entry is to be inserted.| +| element | T | Yes| Target element.| +| index | number | Yes| Index of the position where the element is to be inserted.| **Example** @@ -119,19 +134,21 @@ linkedList.insert(2, true); has(element: T): boolean -Checks whether this container has the specified entry. +Checks whether this container has the specified element. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to check.| +| element | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the specified entry is contained; returns **false** otherwise.| +| boolean | Returns **true** if the specified element is contained; returns **false** otherwise.| **Example** @@ -146,19 +163,21 @@ let result = linkedList.has("Ahfbrgrbgnutfodgorrogorg"); get(index: number): T -Obtains an entry at the specified position in this container. +Obtains an element at the specified position in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry to query.| +| index | number | Yes| Position index of the target element.| **Return value** | Type| Description| | -------- | -------- | -| T | Entry obtained.| +| T | Element obtained.| **Example** @@ -178,19 +197,21 @@ let result = linkedList.get(2); getLastIndexOf(element: T): number -Obtains the index of the last occurrence of the specified entry in this container. +Obtains the index of the last occurrence of the specified element in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to check.| +| element | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| number | Returns the position index if obtained; returns **-1** if the specified entry is not found.| +| number | Returns the position index if obtained; returns **-1** otherwise.| **Example** @@ -210,19 +231,21 @@ let result = linkedList.getLastIndexOf(2); getIndexOf(element: T): number -Obtains the index of the first occurrence of the specified entry in this container. +Obtains the index of the first occurrence of the specified element in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to check.| +| element | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| number | Returns the position index if obtained; returns **-1** if the specified entry is not found.| +| number | Returns the position index if obtained; returns **-1** otherwise.| **Example** @@ -242,19 +265,21 @@ let result = linkedList.getIndexOf(2); removeByIndex(index: number): T -Removes an entry at the specified position from this container. +Removes an element at the specified position from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry to remove.| +| index | number | Yes| Position index of the target element.| **Return value** | Type| Description| | -------- | -------- | -| T | Entry removed.| +| T | Element removed.| **Example** @@ -272,13 +297,15 @@ let result = linkedList.removeByIndex(2); removeFirst(): T -Removes the first entry from this container. +Removes the first element from this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Type| Description| | -------- | -------- | -| T | Entry removed.| +| T | Element removed.| **Example** @@ -296,13 +323,15 @@ let result = linkedList.removeFirst(); removeLast(): T -Removes the last entry from this container. +Removes the last element from this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Type| Description| | -------- | -------- | -| T | Entry removed.| +| T | Element removed.| **Example** @@ -320,19 +349,21 @@ let result = linkedList.removeLast(); remove(element: T): boolean -Removes the first occurrence of the specified entry from this container. +Removes the first occurrence of the specified element from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to check.| +| element | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the entry is removed successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is removed successfully; returns **false** otherwise.| **Example** @@ -349,19 +380,21 @@ let result = linkedList.remove(2); removeFirstFound(element: T): boolean -Removes the first occurrence of the specified entry from this container. +Removes the first occurrence of the specified element from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to check.| +| element | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the entry is removed successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is removed successfully; returns **false** otherwise.| **Example** @@ -378,19 +411,21 @@ let result = linkedList.removeFirstFound(4); removeLastFound(element: T): boolean -Removes the last occurrence of the specified entry from this container. +Removes the last occurrence of the specified element from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to check.| +| element | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the entry is removed successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is removed successfully; returns **false** otherwise.| **Example** @@ -409,6 +444,8 @@ clone(): LinkedList<T> Clones this container and returns a copy. The modification to the copy does not affect the original instance. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -431,21 +468,23 @@ let result = linkedList.clone(); forEach(callbackfn: (value: T, index?: number, LinkedList?: LinkedList<T>) => void, thisArg?: Object): void -Uses a callback to traverse the entries in this container and obtain their position indexes. +Uses a callback to traverse the elements in this container and obtain their position indexes. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.| +| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Value of the entry that is currently traversed.| -| index | number | No| Position index of the entry that is currently traversed.| +| value | T | Yes| Value of the element that is currently traversed.| +| index | number | No| Position index of the element that is currently traversed.| | LinkedList | LinkedList<T> | No| Instance that invokes the **forEach** API.| **Example** @@ -457,7 +496,7 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); linkedList.forEach((value, index) => { - console.log(value, index); + console.log("value:" + value, index); }); ``` @@ -467,6 +506,8 @@ clear(): void Clears this container and sets its length to **0**. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -482,20 +523,22 @@ linkedList.clear(); set(index: number, element: T): T -Replaces an entry at the specified position in this container with a given entry. +Replaces an element at the specified position in this container with a given element. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry to replace.| -| element | T | Yes| Entry to be used for replacement.| +| index | number | Yes| Position index of the target element.| +| element | T | Yes| Element to be used for replacement.| **Return value** | Type| Description| | -------- | -------- | -| T | New entry.| +| T | New element.| **Example** @@ -514,6 +557,8 @@ convertToArray(): Array<T> Converts this container into an array. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -534,13 +579,15 @@ let result = linkedList.convertToArray(); getFirst(): T -Obtains the first entry in this container. +Obtains the first element in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Type| Description| | -------- | -------- | -| T | Returns the entry if obtained; returns **undefined** otherwise.| +| T | Returns the element if obtained; returns **undefined** otherwise.| **Example** @@ -557,13 +604,15 @@ let result = linkedList.getFirst(); getLast(): T -Obtains the last entry in this container. +Obtains the last element in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Type| Description| | -------- | -------- | -| T | Returns the entry if obtained; returns **undefined** otherwise.| +| T | Returns the element if obtained; returns **undefined** otherwise.| **Example** @@ -580,9 +629,10 @@ linkedList.getLast(); [Symbol.iterator]\(): IterableIterator<T> - Obtains an iterator, each item of which is a JavaScript object. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -600,14 +650,14 @@ linkedList.add(4); // Method 1: for (let item of linkedList) { - console.log(item); + console.log("value:" + item); } // Method 2: let iter = linkedList[Symbol.iterator](); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value:" + temp); temp = iter.next().value; } ``` diff --git a/en/application-dev/reference/apis/js-apis-list.md b/en/application-dev/reference/apis/js-apis-list.md index 661d0726ebe52f5e5fc97d68cca866938bc2660a..dfd940b660fe213cf114a7a2b3391c75eb608c5e 100644 --- a/en/application-dev/reference/apis/js-apis-list.md +++ b/en/application-dev/reference/apis/js-apis-list.md @@ -1,28 +1,31 @@ # Linear Container List -> ![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. +**List** is implemented based on the singly linked list. Each node has a reference pointing to the next element. When querying an element, the system traverses the list from the beginning. **List** offers efficient insertion and removal operations but supports low query efficiency. **List** allows null elements. + +Unlike [LinkedList](js-apis-linkedlist.md), which is a doubly linked list, **List** is a singly linked list that does not support insertion or removal at both ends. + +**Recommended use case**: Use **List** for frequent insertion and removal operations. ## Modules to Import ```ts -import List from '@ohos.util.List' +import List from '@ohos.util.List'; ``` -## System Capabilities - -SystemCapability.Utils.Lang - ## List - ### Attributes +**System capability**: SystemCapability.Utils.Lang + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Number of entries in a list (called container later).| +| length | number | Yes| No| Number of elements in a list (called container later).| ### constructor @@ -31,6 +34,8 @@ constructor() A constructor used to create a **List** instance. +**System capability**: SystemCapability.Utils.Lang + **Example** @@ -43,19 +48,21 @@ let list = new List(); add(element: T): boolean -Adds an entry at the end of this container. +Adds an element at the end of this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Element to add.| +| element | T | Yes| Target element.| **Return value** | Value Type | Description| | -------- | -------- | -| boolean | Returns **true** if the entry is added successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is added successfully; returns **false** otherwise.| **Example** @@ -73,14 +80,16 @@ let result3 = list.add(false); insert(element: T, index: number): void -Inserts an entry at the specified position in this container. +Inserts an element at the specified position in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Element to insert.| -| index | number | Yes| Index of the position where the entry is to be inserted.| +| element | T | Yes| Target element.| +| index | number | Yes| Index of the position where the element is to be inserted.| **Example** @@ -95,19 +104,21 @@ list.insert(true, 2); has(element: T): boolean -Checks whether this container has the specified entry. +Checks whether this container has the specified element. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to check.| +| element | T | Yes| Target element.| **Return value** | Value Type | Description| | -------- | -------- | -| boolean | Returns **true** if the specified entry is contained; returns **false** otherwise.| +| boolean | Returns **true** if the specified element is contained; returns **false** otherwise.| **Example** @@ -122,19 +133,21 @@ let result1 = list.has("Ahfbrgrbgnutfodgorrogorg"); get(index: number): T -Obtains the entry at the specified position in this container. +Obtains the element at the specified position in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry to obtain.| +| index | number | Yes| Position index of the target element.| **Return value** | Value Type | Description| | -------- | -------- | -| T | Entry obtained.| +| T | Element obtained.| **Example** @@ -154,19 +167,21 @@ let result = list.get(2); getLastIndexOf(element: T): number -Obtains the index of the last occurrence of the specified entry in this container. +Obtains the index of the last occurrence of the specified element in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to obtain.| +| element | T | Yes| Target element.| **Return value** | Value Type | Description| | -------- | -------- | -| number | Returns the position index if obtained; returns **-1** if the specified entry is not found.| +| number | Returns the position index if obtained; returns **-1** otherwise.| **Example** @@ -186,19 +201,21 @@ let result = list.getLastIndexOf(2); getIndexOf(element: T): number -Obtains the index of the first occurrence of the specified entry in this container. +Obtains the index of the first occurrence of the specified element in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to obtain.| +| element | T | Yes| Target element.| **Return value** | Value Type | Description| | -------- | -------- | -| number | Returns the position index if obtained; returns **-1** if the specified entry is not found.| +| number | Returns the position index if obtained; returns **-1** otherwise.| **Example** @@ -221,6 +238,8 @@ equal(obj: Object): boolean Compares whether a specified object is equal to this container. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Value Type | Mandatory| Description| @@ -254,19 +273,21 @@ let result = list.equal(obj2); removeByIndex(index: number): T -Removes an entry at the specified position from this container. +Removes an element at the specified position from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry to remove.| +| index | number | Yes| Position index of the target element.| **Return value** | Value Type | Description| | -------- | -------- | -| T | Entry removed.| +| T | Element removed.| **Example** @@ -284,19 +305,21 @@ let result = list.removeByIndex(2); remove(element: T): boolean -Removes the first occurrence of the specified entry from this container. +Removes the first occurrence of the specified element from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to remove.| +| element | T | Yes| Target element.| **Return value** | Value Type | Description| | -------- | -------- | -| boolean | Returns **true** if the entry is removed successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is removed successfully; returns **false** otherwise.| **Example** @@ -314,7 +337,9 @@ let result = list.remove(2); replaceAllElements(callbackfn: (value: T, index?: number, list?: List<T>) => T, thisArg?: Object): void -Replaces all entries in this container with new entries, and returns the new ones. +Replaces all elements in this container with new elements, and returns the new ones. + +**System capability**: SystemCapability.Utils.Lang **Parameters** @@ -327,8 +352,8 @@ callbackfn | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Value of the entry that is currently traversed.| -| index | number | No| Position index of the entry that is currently traversed.| +| value | T | Yes| Value of the element that is currently traversed.| +| index | number | No| Position index of the element that is currently traversed.| | list | List<T> | No| Instance that invokes the **replaceAllElements** method.| **Example** @@ -352,21 +377,23 @@ list.replaceAllElements((value, index) => { forEach(callbackfn: (value: T, index?: number, List?: List<T>) => void, thisArg?: Object): void -Uses a callback to traverse the entries in this container and obtain their position indexes. +Uses a callback to traverse the elements in this container and obtain their position indexes. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.| +| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Value of the entry that is currently traversed.| -| index | number | No| Position index of the entry that is currently traversed.| +| value | T | Yes| Value of the element that is currently traversed.| +| index | number | No| Position index of the element that is currently traversed.| | List | List<T> | No| Instance that invokes the **forEach** method.| **Example** @@ -378,7 +405,7 @@ list.add(4); list.add(5); list.add(4); list.forEach((value, index) => { - console.log(value, index); + console.log("value: " + value, index); }); ``` @@ -387,20 +414,22 @@ list.forEach((value, index) => { sort(comparator: (firstValue: T, secondValue: T) => number): void -Sorts entries in this container. +Sorts elements in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** -| Name | Type | Mandatory | Description | +| Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| comparator | function | Yes | Callback invoked for sorting. | +| comparator | function | Yes| Callback invoked for sorting.| comparator -| Name | Type | Mandatory | Description | +| Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| firstValue | T | Yes | Previous entry. | -| secondValue | T | Yes | Next entry. | +| firstValue | T | Yes| Previous element.| +| secondValue | T | Yes| Next element.| **Example** @@ -410,15 +439,17 @@ list.add(2); list.add(4); list.add(5); list.add(4); -list.sort(a, (b => a - b)); -list.sort(a, (b => b - a)); +list.sort((a, b) => a - b); +list.sort((a, b) => b - a); ``` ### getSubList getSubList(fromIndex: number, toIndex: number): List<T> -Obtains entries within a range in this container, including the entry at the start position but not that at the end position, and returns these entries as a new **List** instance. +Obtains elements within a range in this container, including the element at the start position but not that at the end position, and returns these elements as a new **List** instance. + +**System capability**: SystemCapability.Utils.Lang **Parameters** @@ -452,6 +483,8 @@ clear(): void Clears this container and sets its length to **0**. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -467,20 +500,22 @@ list.clear(); set(index: number, element: T): T -Replaces an entry at the specified position in this container with a given entry. +Replaces an element at the specified position in this container with a given element. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry to replace.| -| element | T | Yes| Entry to be used for replacement.| +| index | number | Yes| Position index of the target element.| +| element | T | Yes| Element to be used for replacement.| **Return value** | Value Type | Description| | -------- | -------- | -| T | New entry.| +| T | New element.| **Example** @@ -500,11 +535,13 @@ convertToArray(): Array<T> Converts this container into an array. +**System capability**: SystemCapability.Utils.Lang + **Return value** -| Type | Description | +| Value Type | Description| | -------- | -------- | -| Array<T> | Array obtained. | +| Array<T> | Array obtained.| **Example** @@ -521,7 +558,9 @@ let result = list.convertToArray(); isEmpty(): boolean -Checks whether this container is empty (contains no entry). +Checks whether this container is empty (contains no element). + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -544,13 +583,15 @@ let result = list.isEmpty(); getFirst(): T -Obtains the first entry in this container. +Obtains the first element in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Value Type | Description| | -------- | -------- | -| T | The first entry obtained.| +| T | The first element obtained.| **Example** @@ -567,13 +608,15 @@ let result = list.getFirst(); getLast(): T -Obtains the last entry in this container. +Obtains the last element in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Value Type | Description| | -------- | -------- | -| T | The last entry obtained.| +| T | The last element obtained.| **Example** @@ -590,9 +633,10 @@ let result = list.getLast(); [Symbol.iterator]\(): IterableIterator<T> - Obtains an iterator, each item of which is a JavaScript object. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Value Type | Description| @@ -610,14 +654,14 @@ list.add(4); // Method 1: for (let item of list) { - console.log(item); + console.log("value: " + item); } // Method 2: let iter = list[Symbol.iterator](); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value: " + temp); temp = iter.next().value; } ``` diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 90041e190287f35f80ed0913690a8cdc3b11ae45..2b0504a51b86410317627cb2dc7d3429bb3c6e1c 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -117,7 +117,7 @@ Creates an **AudioRecorder** instance to control audio recording. **Example** ```js -let audiorecorder = media.createAudioRecorder(); +let audioRecorder = media.createAudioRecorder(); ``` ## media.createVideoRecorder9+ @@ -679,6 +679,8 @@ setDisplaySurface(surfaceId: string, callback: AsyncCallback\): void Sets **SurfaceId**. This API uses a callback to return the result. +*Note: **SetDisplaySurface** must be called between the URL setting and the calling of **prepare**. A surface must be set for video streams without audio. Otherwise, the calling of **prepare** fails. + **System capability**: SystemCapability.Multimedia.Media.VideoPlayer **Parameters** @@ -706,6 +708,8 @@ setDisplaySurface(surfaceId: string): Promise\ Sets **SurfaceId**. This API uses a promise to return the result. +*Note: **SetDisplaySurface** must be called between the URL setting and the calling of **prepare**. A surface must be set for video streams without audio. Otherwise, the calling of **prepare** fails. + **System capability**: SystemCapability.Multimedia.Media.VideoPlayer **Parameters** @@ -716,9 +720,9 @@ Sets **SurfaceId**. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------- | ------------------------------ | -| Promise | Promise used to return the result.| +| Type | Description | +| -------------- | ------------------------------ | +| Promise\ | Promise used to return the result.| **Example** @@ -1679,34 +1683,34 @@ let audioRecorderConfig = { uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. location : { latitude : 30, longitude : 130}, } -audioRecorder.on('error', (error) => { // Set the 'error' event callback. +audioRecorder.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}`); }); -audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. +audioRecorder.on('prepare', () => { // Set the prepare event callback. console.log('prepare success'); - audioRecorder.start(); // Start recording and trigger the 'start' event callback. + audioRecorder.start(); // Start recording and trigger the start event callback. }); -audioRecorder.on('start', () => { // Set the 'start' event callback. +audioRecorder.on('start', () => { // Set the start event callback. console.log('audio recorder start success'); }); -audioRecorder.on('pause', () => { // Set the 'pause' event callback. +audioRecorder.on('pause', () => { // Set the pause event callback. console.log('audio recorder pause success'); }); -audioRecorder.on('resume', () => { // Set the 'resume' event callback. +audioRecorder.on('resume', () => { // Set the resume event callback. console.log('audio recorder resume success'); }); -audioRecorder.on('stop', () => { // Set the 'stop' event callback. +audioRecorder.on('stop', () => { // Set the stop event callback. console.log('audio recorder stop success'); }); -audioRecorder.on('release', () => { // Set the 'release' event callback. +audioRecorder.on('release', () => { // Set the release event callback. console.log('audio recorder release success'); }); -audioRecorder.on('reset', () => { // Set the 'reset' event callback. +audioRecorder.on('reset', () => { // Set the reset event callback. console.log('audio recorder reset success'); }); -audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the 'prepare' event callback. +audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the prepare event callback. ``` ### on('error') @@ -1727,12 +1731,12 @@ Subscribes to the audio recording error event. **Example** ```js -audioRecorder.on('error', (error) => { // Set the 'error' event callback. +audioRecorder.on('error', (error) => { // Set the error event callback. console.info(`audio error called, errName is ${error.name}`); // Print the error name. console.info(`audio error called, errCode is ${error.code}`); // Print the error code. console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type. }); -audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the 'error' event callback. +audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the error event callback. ``` ## AudioRecorderConfig @@ -1749,7 +1753,7 @@ Describes audio recording configurations. | numberOfChannels | number | No | Number of audio channels. The default value is **2**. | | format | [AudioOutputFormat](#audiooutputformat) | No | Audio output format. The default value is **MPEG_4**. | | location | [Location](#location) | No | Geographical location of the recorded audio. | -| uri | string | Yes | Audio output URI. Supported: fd://xx (fd number)
![en-us_image_0000001164217678](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| +| uri | string | Yes | Audio output URI. Supported: fd://xx (fd number)
![en-us_image_0000001164217678](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| | audioEncoderMime | [CodecMimeType](#codecmimetype8) | No | Audio encoding format. | @@ -2347,7 +2351,7 @@ Subscribes to the video recording error event. **Example** ```js -videoRecorder.on('error', (error) => { // Set the 'error' event callback. +videoRecorder.on('error', (error) => { // Set the error event callback. console.info(`audio error called, errName is ${error.name}`); // Print the error name. console.info(`audio error called, errCode is ${error.code}`); // Print the error code. console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type. @@ -2383,7 +2387,7 @@ Describes the video recording parameters. | profile | [VideoRecorderProfile](#videorecorderprofile9) | Yes | Video recording profile. | | rotation | number | No | Rotation angle of the recorded video. | | location | [Location](#location) | No | Geographical location of the recorded video. | -| url | string | Yes | Video output URL. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| +| url | string | Yes | Video output URL. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| ## AudioSourceType9+ @@ -2434,7 +2438,7 @@ Enumerates the container format types (CFTs). | Name | Value | Description | | ----------- | ----- | --------------------- | -| CFT_MPEG_4 | "mp4" | Video container format MPEG-4 .| +| CFT_MPEG_4 | "mp4" | Video container format MPEG-4.| | CFT_MPEG_4A | "m4a" | Audio container format M4A.| ## Location diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index 6b1b11f9e17627eea877edf5b34b25551f25ce24..3d2f6f3e9703e606847e92822c62aa20c2811e8f 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -1,6 +1,7 @@ -# Media Library Management +# MediaLibrary -> **NOTE**
+> **NOTE** +> > This component is supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -28,7 +29,13 @@ Obtains a **MediaLibrary** instance, which is used to access and modify personal | ----------------------------- | :---- | | [MediaLibrary](#medialibrary) | **MediaLibrary** instance.| -**Example** +**Example (from API version 9)** + +``` +var media = mediaLibrary.getMediaLibrary(this.context); +``` + +**Example (API version 8)** ``` import featureAbility from '@ohos.ability.featureAbility'; @@ -87,7 +94,7 @@ let imagesfetchOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], }; -mediaLibrary.getFileAssets(imagesfetchOp, (error, fetchFileResult) => { +media.getFileAssets(imagesfetchOp, (error, fetchFileResult) => { if (fetchFileResult != undefined) { console.info('mediaLibraryTest : ASSET_CALLBACK fetchFileResult success'); fetchFileResult.getAllObject((err, fileAssetList) => { @@ -129,7 +136,7 @@ let imagesfetchOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], }; -mediaLibrary.getFileAssets(imagesfetchOp).then(function(fetchFileResult){ +media.getFileAssets(imagesfetchOp).then(function(fetchFileResult){ console.info("getFileAssets successfully:"+ JSON.stringify(dir)); }).catch(function(err){ console.info("getFileAssets failed with error:"+ err); @@ -176,7 +183,7 @@ Unsubscribes from the media library changes. This API uses an asynchronous callb **Example** ``` -mediaLibrary.off('imageChange', () => { +media.off('imageChange', () => { // stop listening success }) ``` @@ -246,7 +253,7 @@ Creates a media asset. This API uses a promise to return the result. ``` async function example() { - // Create an image file in promise mode + // Create an image file in promise mode. let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; const path = await media.getPublicDirectory(DIR_IMAGE); @@ -344,7 +351,7 @@ let AlbumNoArgsfetchOp = { selections: '', selectionArgs: [], }; -mediaLibrary.getAlbums(AlbumNoArgsfetchOp, (err, albumList) => { +media.getAlbums(AlbumNoArgsfetchOp, (err, albumList) => { if (albumList != undefined) { const album = albumList[0]; console.info('album.albumName = ' + album.albumName); @@ -384,7 +391,7 @@ let AlbumNoArgsfetchOp = { selections: '', selectionArgs: [], }; -mediaLibrary.getAlbums(AlbumNoArgsfetchOp).then(function(albumList){ +media.getAlbums(AlbumNoArgsfetchOp).then(function(albumList){ console.info("getAlbums successfully:"+ JSON.stringify(albumList)); }).catch(function(err){ console.info("getAlbums failed with error:"+ err); @@ -433,17 +440,16 @@ Call this API when you no longer need to use the APIs in the **MediaLibrary** in **Example** ``` -var media = mediaLibrary.getMediaLibrary(context); media.release() ``` -### storeMediaAsset +### storeMediaAsset(deprecated) storeMediaAsset(option: MediaAssetOption, callback: AsyncCallback<string>): void Stores a media asset. This API uses an asynchronous callback to return the URI that stores the media asset. -This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. +> **NOTE**
This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -467,19 +473,19 @@ mediaLibrary.getMediaLibrary().storeMediaAsset(option, (err, value) => { console.log("An error occurred when storing the media asset."); return; } - console.log("Media asset stored. "); + console.log("Media asset stored."); // Obtain the URI that stores the media asset. }); ``` -### storeMediaAsset +### storeMediaAsset(deprecated) storeMediaAsset(option: MediaAssetOption): Promise<string> Stores a media asset. This API uses a promise to return the URI that stores the media asset. -This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. +> **NOTE**
This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -512,13 +518,13 @@ mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => { ``` -### startImagePreview +### startImagePreview(deprecated) startImagePreview(images: Array<string>, index: number, callback: AsyncCallback<void>): 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 an asynchronous callback to return the execution result. -This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. +> **NOTE**
This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -526,7 +532,7 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. It will be a | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------------------------------- | -| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **https://** or **dataability://**.| +| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **dataability://** or **https://**.| | index | number | Yes | Index of the first image to preview. | | callback | AsyncCallback<void> | Yes | Callback used to return the image preview result. If the preview fails, an error message is returned. | @@ -537,7 +543,7 @@ let images = [ "dataability:///media/xxxx/2", "dataability:///media/xxxx/3" ]; -/* Online image usage mode +/* Preview online images. let images = [ "https://media.xxxx.com/image1.jpg", "https://media.xxxx.com/image2.jpg" @@ -554,13 +560,13 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, index, (err) => { ``` -### startImagePreview +### startImagePreview(deprecated) startImagePreview(images: Array<string>, callback: AsyncCallback<void>): void 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. -This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. +> **NOTE**
This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -578,7 +584,7 @@ let images = [ "dataability:///media/xxxx/2", "dataability:///media/xxxx/3" ]; -/* Online image usage mode +/* Preview online images. let images = [ "https://media.xxxx.com/image1.jpg", "https://media.xxxx.com/image2.jpg" @@ -594,13 +600,13 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, (err) => { ``` -### startImagePreview +### startImagePreview(deprecated) 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. -This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. +> **NOTE**
This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -608,7 +614,7 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. It will be a | Name | Type | Mandatory | Description | | ------ | ------------------- | ---- | ---------------------------------------- | -| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **https://** or **dataability://**.| +| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **dataability://** or **https://**.| | index | number | No | Index of the first image to preview. If this parameter is not specified, the default value **0** is used. | **Return value** @@ -624,7 +630,7 @@ let images = [ "dataability:///media/xxxx/2", "dataability:///media/xxxx/3" ]; -/* Online image usage mode +/* Preview online images. let images = [ "https://media.xxxx.com/image1.jpg", "https://media.xxxx.com/image2.jpg" @@ -639,13 +645,13 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => { ``` -### startMediaSelect +### startMediaSelect(deprecated) startMediaSelect(option: MediaSelectOption, callback: AsyncCallback<Array<string>>): void Starts media selection. This API uses an asynchronous callback to return the list of URIs that store the selected media assets. -This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. +> **NOTE**
This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -674,13 +680,13 @@ mediaLibrary.getMediaLibrary().startMediaSelect(option, (err, value) => { ``` -### startMediaSelect +### startMediaSelect(deprecated) 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. -This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. +> **NOTE**
This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -723,7 +729,7 @@ Provides APIs for encapsulating file asset attributes. | Name | Type | Readable| Writable| Description | | ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ | | id | number | Yes | No | File asset ID. | -| uri | string | Yes | No | File asset URI, for example, dataability:///media/image/2. | +| uri | string | Yes | No | File asset URI, for example, **dataability:///media/image/2**. | | mimeType | string | Yes | No | Extended file attributes. | | mediaType8+ | [MediaType](#mediatype8) | Yes | No | Media type. | | displayName | string | Yes | Yes | Display file name, including the file name extension. | @@ -821,7 +827,7 @@ async function example() { commitModify(callback: AsyncCallback<void>): void -Commits the modification of this file asset to the database. This API uses an asynchronous callback to return the result. +Commits the modification in this file asset to the database. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA @@ -857,7 +863,7 @@ async function example() { commitModify(): Promise<void> -Commits the modification of this file asset to the database. This API uses a promise to return the result. +Commits the modification in this file asset to the database. This API uses a promise to return the result. **Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA @@ -893,6 +899,8 @@ 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. + **Required permissions**: ohos.permission.READ_MEDIA (when **mode** is set to **r**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **w**) **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -901,7 +909,7 @@ Opens this file asset. This API uses an asynchronous callback to return the resu | 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).| | callback | AsyncCallback<number> | Yes | Callback used to return the file handle. | **Example** @@ -928,6 +936,8 @@ 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. + **Required permissions**: ohos.permission.READ_MEDIA (when **mode** is set to **r**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **w**) **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -1009,7 +1019,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 (when **mode** is set to **'r'**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **'w'**) **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -1531,7 +1541,7 @@ Checks whether the cursor is in the last row of the result set. | Type | Description | | ------- | ---------------------------------- | -| boolean | Returns **true** if the cursor is in the last row of the result set; returns *false** otherwise.| +| boolean | Returns **true** if the cursor is in the last row of the result set; returns *false* otherwise.| **Example** @@ -1566,7 +1576,7 @@ async function example() { close(): void -Releases and invalidates this **FetchFileResult** instance. Other APIs cannot be invoked after the instance is released. +Releases and invalidates this **FetchFileResult** instance. Other APIs in this instance cannot be invoked after it is released. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -1947,7 +1957,7 @@ async function example() { Provides APIs to implement a physical album. -### **Attributes** +### Attributes **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -1965,7 +1975,7 @@ Provides APIs to implement a physical album. commitModify(callback: AsyncCallback<void>): void -Commits the modification of the album attributes to the database. This API uses an asynchronous callback to return the result. +Commits the modification in the album attributes to the database. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA @@ -2002,7 +2012,7 @@ async function example() { commitModify(): Promise<void> -Commits the modification of the album attributes to the database. This API uses a promise to return the result. +Commits the modification in the album attributes to the database. This API uses a promise to return the result. **Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA @@ -2204,7 +2214,7 @@ Describes options for fetching media files. | ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ | | selections | string | Yes | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?',| | selectionArgs | Array<string> | Yes | Yes | Yes | Value of the condition, which corresponds to the value of the condition column in **selections**.
Example:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | -| order8+ | string | Yes | Yes | No | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example:
Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " AESC"
Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC"| +| order | string | Yes | Yes | No | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example:
Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " AESC"
Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC"| | uri8+ | string | Yes | Yes | No | File URI. | | networkId8+ | string | Yes | Yes | No | Network ID of the registered device. | | extendArgs8+ | string | Yes | Yes | No | Extended parameters for fetching the files. Currently, no extended parameters are available. | @@ -2218,30 +2228,30 @@ Describes the image size. | width | number | Yes | Yes | Image width, in pixels.| | height | number | Yes | Yes | Image height, in pixels.| -## MediaAssetOption +## MediaAssetOption(deprecated) Implements the media asset option. -This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. +> **NOTE**
This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Type | Mandatory | Description | -| ------------ | ------ | ---- | ---------------------------------------- | -| src | string | Yes | Absolute path of the local file of the application. | -| mimeType | string | Yes | Multipurpose Internet Mail Extensions (MIME) type of the media.
The value can be 'image/\*', 'video/\*', 'audio/\*' or 'file\*'.| -| relativePath | string | No | Custom path for storing media assets, for example, 'Pictures/'. If this parameter is unspecified, media assets are stored in the default path.
Default path of images: 'Pictures/'
Default path of videos: 'Videos/'
Default path of audios: 'Audios/'
Default path of files: 'Documents/'| +| Name | Type | Mandatory| Description | +| ------------ | ------ | ---- | ------------------------------------------------------------ | +| src | string | Yes | Application sandbox oath of the local file. | +| mimeType | string | Yes | Multipurpose Internet Mail Extensions (MIME) type of the media.
The value can be 'image/\*', 'video/\*', 'audio/\*' or 'file\*'.| +| relativePath | string | No | Custom path for storing media assets, for example, 'Pictures/'. If this parameter is unspecified, media assets are stored in the default path.
Default path of images: 'Pictures/'
Default path of videos: 'Videos/'
Default path of audios: 'Audios/'
Default path of files: 'Documents/'| -## MediaSelectOption +## MediaSelectOption(deprecated) Describes media selection option. -This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. +> **NOTE**
This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core | Name | Type | Mandatory | Description | | ----- | ------ | ---- | -------------------- | | type | string | Yes | Media type, which can be **image**, **media**, or **video**. Currently, only **media** is supported.| -| count | number | Yes | Number of media assets selected. If **count** is set to **1**, one media asset can be selected. If **count** is greater than **1**, multiple media assets can be selected. | +| count | number | Yes | Number of media assets selected. The value starts from 1, which indicates that one media asset can be selected. | diff --git a/en/application-dev/reference/apis/js-apis-mediaquery.md b/en/application-dev/reference/apis/js-apis-mediaquery.md index 7cb3263efc4800810a185bf908ae98fef33808ec..1f754aa69bee3f93a3420df473d06e915a673c4f 100644 --- a/en/application-dev/reference/apis/js-apis-mediaquery.md +++ b/en/application-dev/reference/apis/js-apis-mediaquery.md @@ -1,12 +1,13 @@ # Media Query -> ![icon-note.gif](public_sys-resources/icon-note.gif)**NOTE** +> **NOTE** +> > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import mediaquery from '@ohos.mediaquery' ``` @@ -22,19 +23,19 @@ matchMediaSync(condition: string): MediaQueryListener Sets the media query criteria and returns the corresponding listening handle. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | condition | string | Yes| Matching condition of a media event.| +**Parameters** +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ---------- | +| condition | string | Yes | Matching condition of a media event.| -- Return value - | Type| Description| - | -------- | -------- | - | MediaQueryListener | Listening handle to a media event, which is used to register or unregister the listening callback.| +**Return value** +| Type | Description | +| ------------------ | ---------------------- | +| MediaQueryListener | Listening handle to a media event, which is used to register or unregister the listening callback.| -- Example - ``` - listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. +**Example** + ```js +listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. ``` @@ -45,10 +46,10 @@ Media query handle, including the first query result when the handle is applied ### Attributes -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| matches | boolean | Yes| No| Whether the match condition is met.| -| media | string | Yes| No| Matching condition of a media event.| +| Name | Type | Readable | Writable | Description | +| ------- | ------- | ---- | ---- | ---------- | +| matches | boolean | Yes | No | Whether the match condition is met. | +| media | string | Yes | No | Matching condition of a media event.| ### on @@ -57,13 +58,13 @@ on(type: 'change', callback: Callback<MediaQueryResult>): void Registers a callback with the corresponding query condition by using the handle. This callback is triggered when the media attributes change. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Must enter the string **change**.| - | callback | Callback<MediaQueryResult> | Yes| Callback registered with media query.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | ---- | ---------------- | +| type | string | Yes | Must enter the string **change**.| +| callback | Callback<MediaQueryResult> | Yes | Callback registered with media query. | -- Example +**Example** For details, see [off Example](#off). @@ -72,14 +73,14 @@ Registers a callback with the corresponding query condition by using the handle. off(type: 'change', callback?: Callback<MediaQueryResult>): void Unregisters a callback with the corresponding query condition by using the handle, so that no callback is triggered when the media attributes change. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | boolean | Yes| Must enter the string **change**.| - | callback | Callback<MediaQueryResult> | No| Callback to be unregistered. If the default value is used, all callbacks of the handle are unregistered.| - -- Example - ``` +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | ---- | ----------------------------- | +| type | boolean | Yes | Must enter the string **change**. | +| callback | Callback<MediaQueryResult> | No | Callback to be unregistered. If the default value is used, all callbacks of the handle are unregistered.| + +**Example** + ```js import mediaquery from '@ohos.mediaquery' listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. @@ -90,8 +91,8 @@ Unregisters a callback with the corresponding query condition by using the handl // do something here } } - this.listener.on('change', this.onPortrait) // Registration callback. - this.listener.off('change', this.onPortrait) // Deregistration callback. + listener.on('change', onPortrait) // Register a callback. + listener.off('change', onPortrait) // Unregister a callback. ``` @@ -100,15 +101,15 @@ Unregisters a callback with the corresponding query condition by using the handl ### Attributes -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| matches | boolean | Yes| No| Whether the match condition is met.| -| media | string | Yes| No| Matching condition of a media event.| +| Name | Type | Readable | Writable | Description | +| ------- | ------- | ---- | ---- | ---------- | +| matches | boolean | Yes | No | Whether the match condition is met. | +| media | string | Yes | No | Matching condition of a media event.| ### Example -``` +```js import mediaquery from '@ohos.mediaquery' let portraitFunc = null diff --git a/en/application-dev/reference/apis/js-apis-missionManager.md b/en/application-dev/reference/apis/js-apis-missionManager.md index 75c79e3af3da6181c1a81f374cdd3730e95a4191..314d2f63cca7d6139a941ca82a1e723a496f0613 100644 --- a/en/application-dev/reference/apis/js-apis-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-missionManager.md @@ -1,7 +1,8 @@ # missionManager -> **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. missionManager provides APIs to lock, unlock, and clear missions, and switch a mission to the foreground. @@ -26,15 +27,15 @@ Registers a listener to observe the mission status. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| listener | MissionListener | Yes| Listener to register.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | listener | MissionListener | Yes| Listener to register.| **Return value** -| Type| Description| -| -------- | -------- | -| number | Returns the unique index of the mission status listener, which is created by the system and allocated when the listener is registered.| + | Type| Description| + | -------- | -------- | + | number | Returns the unique index of the mission status listener, which is created by the system and allocated when the listener is registered.| **Example** @@ -62,10 +63,10 @@ Deregisters a mission status listener. This API uses an asynchronous callback to **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -96,15 +97,15 @@ Deregisters a mission status listener. This API uses a promise to return the res **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| **Example** @@ -135,11 +136,11 @@ Obtains the information about a given mission. This API uses an asynchronous cal **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceId | string | Yes| Device ID. It is a null string by default for the local device.| -| missionId | number | Yes| Mission ID.| -| callback | AsyncCallback<[MissionInfo](#missioninfo)> | Yes| Callback used to return the mission information obtained.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<[MissionInfo](#missioninfo)> | Yes| Callback used to return the mission information obtained.| **Example** @@ -169,16 +170,16 @@ Obtains the information about a given mission. This API uses a promise to return **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceId | string | Yes| Device ID. It is a null string by default for the local device.| -| missionId | number | Yes| Mission ID.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[MissionInfo](#missioninfo)> | Promise used to return the mission information obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[MissionInfo](#missioninfo)> | Promise used to return the mission information obtained.| **Example** @@ -201,11 +202,11 @@ Obtains information about all missions. This API uses an asynchronous callback t **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceId | string | Yes| Device ID. It is a null string by default for the local device.| -| numMax | number | Yes| Maximum number of missions whose information can be obtained.| -| callback | AsyncCallback<Array<[MissionInfo](#missioninfo)>> | Yes| Callback used to return the array of mission information obtained.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | numMax | number | Yes| Maximum number of missions whose information can be obtained.| + | callback | AsyncCallback<Array<[MissionInfo](#missioninfo)>> | Yes| Callback used to return the array of mission information obtained.| **Example** @@ -230,16 +231,16 @@ Obtains information about all missions. This API uses a promise to return the re **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceId | string | Yes| Device ID. It is a null string by default for the local device.| -| numMax | number | Yes| Maximum number of missions whose information can be obtained.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | numMax | number | Yes| Maximum number of missions whose information can be obtained.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<Array<[MissionInfo](#missioninfo)>> | Promise used to return the array of mission information obtained.| + | Type| Description| + | -------- | -------- | + | Promise<Array<[MissionInfo](#missioninfo)>> | Promise used to return the array of mission information obtained.| **Example** @@ -262,11 +263,11 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceId | string | Yes| Device ID. It is a null string by default for the local device.| -| missionId | number | Yes| Mission ID.| -| callback | AsyncCallback<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| **Example** @@ -297,16 +298,16 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceId | string | Yes| Device ID. It is a null string by default for the local device.| -| missionId | number | Yes| Mission ID.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Promise used to return the snapshot information obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Promise used to return the snapshot information obtained.| **Example** @@ -337,10 +338,10 @@ Locks a given mission. This API uses an asynchronous callback to return the resu **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| missionId | number | Yes| Mission ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -370,15 +371,15 @@ Locks a given mission. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| missionId | number | Yes| Mission ID.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| **Example** @@ -441,15 +442,15 @@ Unlocks a given mission. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| missionId | number | Yes| Mission ID.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| **Example** @@ -483,10 +484,10 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| missionId | number | Yes| Mission ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -516,15 +517,15 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| missionId | number | Yes| Mission ID.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| **Example** @@ -574,9 +575,9 @@ Clears all unlocked missions. This API uses a promise to return the result. **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| **Example** @@ -598,10 +599,10 @@ Switches a given mission to the foreground. This API uses an asynchronous callba **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| missionId | number | Yes| Mission ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -631,11 +632,11 @@ Switches a given mission to the foreground, with the startup parameters for the **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| missionId | number | Yes| Mission ID.| -| options | StartOptions | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + | options | StartOptions | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -665,16 +666,16 @@ Switches a given mission to the foreground, with the startup parameters for the **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| missionId | number | Yes| Mission ID.| -| options | StartOptions | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + | options | StartOptions | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| **Example** @@ -700,13 +701,13 @@ Describes the mission information. **System capability**: SystemCapability.Ability.AbilityBase -| Name| Type| Readable| Writable| Description| +| 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 can be continued on another device. | +| 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 can be continued on another device. | diff --git a/en/application-dev/reference/apis/js-apis-mouseevent.md b/en/application-dev/reference/apis/js-apis-mouseevent.md new file mode 100644 index 0000000000000000000000000000000000000000..86cf6b064028b150ad0ff0313580fa6918903682 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-mouseevent.md @@ -0,0 +1,89 @@ +# Mouse Event + +Represents mouse events reported by an input 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 + +```js +import {Action,Button,Axis,AxisValue,MouseEvent} from '@ohos.multimodalInput.mouseEvent'; +``` + +## Action + +**System capability**: SystemCapability.MultimodalInput.Input.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| CANCEL | number | Yes| No| Cancellation of a mouse action.| +| MOVE | number | Yes| No| Moving of the mouse pointer.| +| BUTTON_DOWN | number | Yes| No| Pressing of a mouse button.| +| BUTTON_UP | number | Yes| No| Release of a mouse button.| +| AXIS_BEGIN | number | Yes| No| Beginning of the axis event associated with the mouse.| +| AXIS_UPDATE | number | Yes| No| Updating of the axis event associated with the mouse.| +| AXIS_END | number | Yes| No| Ending of the axis event associated with the mouse.| + + +## Button + +**System capability**: SystemCapability.MultimodalInput.Input.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| LEFT | number | Yes| No| Left button on the mouse.| +| MIDDLE | number | Yes| No| Middle button on the mouse.| +| RIGHT | number | Yes| No| Right button on the mouse.| +| SIDE | number | Yes| No| Side button on the mouse.| +| EXTRA | number | Yes| No| Extended button on the mouse.| +| FORWARD | number | Yes| No| Forward button on the mouse.| +| BACK | number | Yes| No| Back button on the mouse.| +| TASK | number | Yes| No| Task button on the mouse.| + +## Axis + +**System capability**: SystemCapability.MultimodalInput.Input.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| SCROLL_VERTICAL | number | Yes| No| Vertical scroll axis.| +| SCROLL_HORIZONTAL | number | Yes| No| Horizontal scroll axis.| +| PINCH | number | Yes| No| Pinch axis.| + + +## AxisValue + +**System capability**: SystemCapability.MultimodalInput.Input.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| axis | Axis | Yes| No| Axis type.| +| value | number | Yes| No| Axis value.| + + +## MouseEvent + +**System capability**: SystemCapability.MultimodalInput.Input.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| action | Action | Yes| No| Mouse event action.| +| screenX | number | Yes| No| X coordinate of the mouse pointer on the screen.| +| screenY | number | Yes| No| Y coordinate of the mouse pointer on the screen.| +| windowX | number | Yes| No| X coordinate of the mouse pointer in the window.| +| windowY | number | Yes| No| Y coordinate of the mouse pointer in the window.| +| rawDeltaX | number | Yes| No| X axis offset relative to the previous reported mouse pointer position. When the mouse pointer is at the edge of the screen, the value may be less than the difference of the X coordinate reported twice.| +| rawDeltaY | number | Yes| No| Y axis offset relative to the previous reported mouse pointer position.| +| button | Button | Yes| No| Button that is currently pressed or released.| +| pressedButtons | Button[] | Yes| No| Button that is being pressed.| +| axes | AxisValue[] | Yes| No| All axis data contained in the event.| +| pressedKeys | KeyCode[] | Yes| No| List of pressed keys.| +| ctrlKey | boolean | Yes| No| Whether ctrlKey is being pressed.| +| altKey | boolean | Yes| No| Whether altKey is being pressed.| +| shiftKey | boolean | Yes| No| Whether shiftKey is being pressed.| +| logoKey | boolean | Yes| No| Whether logoKey is being pressed.| +| fnKey | boolean | Yes| No| Whether fnKey is being pressed.| +| capsLock | boolean | Yes| No| Whether capsLock is active.| +| numLock | boolean | Yes| No| Whether numLock is active.| +| scrollLock | boolean | Yes| No| Whether scrollLock is active.| diff --git a/en/application-dev/reference/apis/js-apis-nfcController.md b/en/application-dev/reference/apis/js-apis-nfcController.md new file mode 100644 index 0000000000000000000000000000000000000000..d4c99452483b63a9893905329d4fd1aae0be4505 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-nfcController.md @@ -0,0 +1,148 @@ +# Standard NFC + +Implements Near-Field Communication (NFC). + +> **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** + +``` +import controller from '@ohos.nfc.controller'; +``` + + +## controller.isNfcAvailable + +isNfcAvailable(): boolean + +Checks whether NFC is available. + +**Return value** + +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if NFC is available; returns **false** otherwise.| + + +## controller.openNfc + +openNfc(): boolean + +Opens NFC. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + +## controller.closeNfc + +closeNfc(): boolean + +Closes NFC. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| -------- | ------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +## controller.isNfcOpen + +isNfcOpen(): boolean + +Checks whether NFC is open. + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| -------- | ----------------------------------- | +| boolean | Returns **true** if NFC is open; returns **false** otherwise.| + +## controller.getNfcState + +getNfcState(): NfcState + +Obtains the NFC state. + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| -------- | ---------------------- | +| NfcState | NFC state obtained. For details, see [NfcState](#nfcstate).| + +## controller.on('nfcStateChange') + +on(type: "nfcStateChange", callback: Callback<NfcState>): void + +Subscribes to NFC state changes. + +**System capability**: SystemCapability.Communication.NFC + +**Parameter** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type to subscribe to. The value is **nfcStateChange**.| + | callback | Callback<NfcState> | Yes| Callback invoked to return the NFC state changes.| + + + +## controller.off('nfcStateChange') + +off(type: "nfcStateChange", callback?: Callback<NfcState>): void + +Unsubscribes from the NFC state changes. + +**System capability**: SystemCapability.Communication.NFC + +**Parameter** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type to unsubscribe from. The value is **nfcStateChange**.| +| callback | Callback<NfcState> | No| Callback used to return the NFC state changes. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Example** + + ```js + import nfcController from '@ohos.nfcController'; + + var NFC_STATE_NOTIFY = "nfcStateChange"; + + var recvNfcStateNotifyFunc = result => { + console.info("nfc state receive state: " + result); + } + + // Subscribe to the NFC state changes. + nfcController.on(NFC_STATE_NOTIFY, recvNfcStateNotifyFunc); + + // Unsubscribe from the NFC state changes. + nfcController.off(NFC_STATE_NOTIFY, recvNfcStateNotifyFunc); + ``` + +## NfcState + +Enumerates the NFC states. + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| STATE_OFF | 1 | Off| +| STATE_TURNING_ON | 2 | Turning on| +| STATE_ON | 3 | On| +| STATE_TURNING_OFF | 4 | Turning off| diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md new file mode 100644 index 0000000000000000000000000000000000000000..51731e95e192713e71add3304331475c11dd6629 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -0,0 +1,78 @@ +# Standard NFC Tag + +Manages Near-Field Communication (NFC) tags. + +> **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** + +``` +import tag from '@ohos.nfc.tag'; +``` + + +## tag.getNfcATag + +getNfcATag(tagInfo: TagInfo): NfcATag + +Obtains an **NfcATag** object, which allows access to the tags that use the NFC-A technology. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description**| +| -------- | -------- | +| NfcATag | **NfcATag** object obtained.| + +## tag.getNfcBTag + +getNfcBTag(tagInfo: TagInfo): NfcBTag + +Obtains an **NfcBTag** object, which allows access to the tags that use the NFC-B technology. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| -------- | ---------------- | +| NfcBTag | **NfcBTag** object obtained.| + +## tag.getNfcFTag + +getNfcFTag(tagInfo: TagInfo): NfcFTag + +Obtains an **NfcFTag** object, which allows access to the tags that use the NFC-F technology. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| -------- | ---------------- | +| NfcFTag | **NfcFTag** object obtained.| + +## tag.getNfcVTag + +getNfcVTag(tagInfo: TagInfo): NfcVTag + +Obtains an **NfcVTag** object, which allows access to the tags that use the NFC-V technology. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| -------- | ---------------- | +| NfcVTag | **NfcVTag** object obtained.| diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index 1bd8702edac6a361335c69520bb54e8571224ebb..7912809087579d64ca726be1b9ada1c8ea0129fb 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -1,6 +1,6 @@ # Notification -> ![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. ## Modules to Import @@ -85,6 +85,8 @@ Publishes a notification. This API uses an asynchronous callback to return the r **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -100,7 +102,7 @@ Publishes a notification. This API uses an asynchronous callback to return the r function publishCallback(err) { console.info("==========================>publishCallback=======================>"); } -// ID of the user who receives the notification. +// ID of the user who receives the notification var userId = 1 // NotificationRequest object var notificationRequest = { @@ -125,6 +127,8 @@ Publishes a notification. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -287,6 +291,8 @@ Adds a notification slot. This API uses an asynchronous callback to return the r **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -318,6 +324,8 @@ Adds a notification slot. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Readable| Writable| Type | Mandatory| Description | @@ -397,6 +405,8 @@ Adds multiple notification slots. This API uses an asynchronous callback to retu **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -432,6 +442,8 @@ Adds multiple notification slots. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -669,6 +681,8 @@ Subscribes to a notification with the subscription information specified. This A **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -684,7 +698,7 @@ Subscribes to a notification with the subscription information specified. This A function subscribeCallback(err) { console.info("==========================>subscribeCallback=======================>"); } -function onConsumeCallback(err, data) { +function onConsumeCallback(data) { console.info("==========================>onConsumeCallback=======================>"); } var subscriber = { @@ -706,6 +720,8 @@ Subscribes to a notification with the subscription information specified. This A **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -719,7 +735,7 @@ Subscribes to a notification with the subscription information specified. This A function subscribeCallback(err) { console.info("==========================>subscribeCallback=======================>"); } -function onConsumeCallback(err, data) { +function onConsumeCallback(data) { console.info("==========================>onConsumeCallback=======================>"); } var subscriber = { @@ -738,6 +754,8 @@ Subscribes to a notification with the subscription information specified. This A **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -748,7 +766,7 @@ Subscribes to a notification with the subscription information specified. This A **Example** ```js -function onConsumeCallback(err, data) { +function onConsumeCallback(data) { console.info("==========================>onConsumeCallback=======================>"); } var subscriber = { @@ -769,6 +787,8 @@ Unsubscribes from a notification. This API uses an asynchronous callback to retu **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -782,7 +802,7 @@ Unsubscribes from a notification. This API uses an asynchronous callback to retu function unsubscribeCallback(err) { console.info("==========================>unsubscribeCallback=======================>"); } -function onConsumeCallback(err, data) { +function onConsumeCallback(data) { console.info("==========================>onConsumeCallback=======================>"); } var subscriber = { @@ -801,6 +821,8 @@ Unsubscribes from a notification. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -810,7 +832,7 @@ Unsubscribes from a notification. This API uses a promise to return the result. **Example** ```js -function onConsumeCallback(err, data) { +function onConsumeCallback(data) { console.info("==========================>onConsumeCallback=======================>"); } var subscriber = { @@ -831,6 +853,8 @@ Sets whether to enable notification for a specified bundle. This API uses an asy **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -861,6 +885,8 @@ Sets whether to enable notification for a specified bundle. This API uses a prom **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -889,6 +915,8 @@ Checks whether notification is enabled for a specified bundle. This API uses an **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -918,6 +946,8 @@ Checks whether notification is enabled for a specified bundle. This API uses a p **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -951,6 +981,8 @@ Checks whether notification is enabled for this application. This API uses an as **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -977,6 +1009,8 @@ Checks whether notification is enabled for this application. This API uses a pro **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1007,6 +1041,8 @@ Sets whether to enable the notification badge for a specified bundle. This API u **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1037,6 +1073,8 @@ Sets the notification slot for a specified bundle. This API uses a promise to re **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1065,6 +1103,8 @@ Checks whether the notification badge is enabled for a specified bundle. This AP **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1094,6 +1134,8 @@ Checks whether the notification badge is enabled for a specified bundle. This AP **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1127,6 +1169,8 @@ Sets the notification slot for a specified bundle. This API uses an asynchronous **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1160,6 +1204,8 @@ Sets the notification slot for a specified bundle. This API uses a promise to re **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1176,7 +1222,7 @@ var bundle = { var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } -Notification.displayBadge(bundle, notificationSlot).then(() => { +Notification.setSlotByBundle(bundle, notificationSlot).then(() => { console.info("==========================>setSlotByBundleCallback=======================>"); }); ``` @@ -1191,6 +1237,8 @@ Obtains the notification slots of a specified bundle. This API uses an asynchron **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1220,6 +1268,8 @@ Obtains the notification slots of a specified bundle. This API uses a promise to **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1253,6 +1303,8 @@ Obtains the number of notification slots of a specified bundle. This API uses an **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1263,7 +1315,7 @@ Obtains the number of notification slots of a specified bundle. This API uses an **Example** ```js -function getSlotNumByBundle(err, data) { +function getSlotNumByBundleCallback(err, data) { console.info("==========================>getSlotNumByBundleCallback=======================>"); } var bundle = { @@ -1282,6 +1334,8 @@ Obtains the number of notification slots of a specified bundle. This API uses a **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1315,6 +1369,8 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1349,6 +1405,8 @@ Removes a notification for a specified bundle. This API uses a promise to return **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1381,6 +1439,8 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1391,6 +1451,8 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal **Example** ```js +var hashCode = 'hashCode' + function removeCallback(err) { console.info("==========================>removeCallback=======================>"); } @@ -1408,6 +1470,8 @@ Removes a notification for a specified bundle. This API uses a promise to return **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1417,6 +1481,8 @@ Removes a notification for a specified bundle. This API uses a promise to return **Example** ```js +var hashCode = 'hashCode' + Notification.remove(hashCode).then(() => { console.info("==========================>removeCallback=======================>"); }); @@ -1432,6 +1498,8 @@ Removes all notifications for a specified bundle. This API uses an asynchronous **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1461,6 +1529,8 @@ Removes all notifications. This API uses an asynchronous callback to return the **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1487,6 +1557,8 @@ Removes all notifications for a specified user. This API uses a promise to retur **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1509,6 +1581,8 @@ Removes all notifications for a specified user. This API uses an asynchronous ca **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1536,6 +1610,8 @@ Removes all notifications for a specified user. This API uses a promise to retur **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1563,6 +1639,8 @@ Obtains all active notifications. This API uses an asynchronous callback to retu **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1589,6 +1667,8 @@ Obtains all active notifications. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Return value** | Type | Description | @@ -1767,6 +1847,8 @@ Removes a notification group for a specified bundle. This API uses an asynchrono **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1798,6 +1880,8 @@ Removes a notification group for a specified bundle. This API uses a promise to **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1825,6 +1909,8 @@ Sets the DND time. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1858,6 +1944,8 @@ Sets the DND time. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Readable| Writable| Type | Mandatory| Description | @@ -1886,6 +1974,8 @@ Sets the DND time for a specified user. This API uses an asynchronous callback t **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1922,6 +2012,8 @@ Sets the DND time for a specified user. This API uses a promise to return the re **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1954,6 +2046,8 @@ Obtains the DND time. This API uses an asynchronous callback to return the resul **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1980,6 +2074,8 @@ Obtains the DND time. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Return value** | Type | Description | @@ -2063,6 +2159,8 @@ Checks whether the DND mode is supported. This API uses an asynchronous callback **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -2089,6 +2187,8 @@ Checks whether the DND mode is supported. This API uses a promise to return the **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Return value** | Type | Description | @@ -2182,11 +2282,11 @@ Requests notification to be enabled for this application. This API uses an async **Example** ```javascript -function requestEnabledNotificationCallback() { +function requestEnableNotificationCallback() { console.log('------------- requestEnabledNotification --------------'); }; -Notification.requestEnabledNotification(requestEnabledNotificationCallback); +Notification.requestEnableNotification(requestEnableNotificationCallback); ``` @@ -2217,6 +2317,8 @@ Sets whether this device supports distributed notifications. This API uses an as **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Type | Mandatory| Description | @@ -2246,6 +2348,8 @@ Sets whether this device supports distributed notifications. This API uses a pro **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Type | Mandatory| Description | @@ -2285,7 +2389,7 @@ function isDistributedEnabledCallback() { console.log('----------- isDistributedEnabled ------------'); }; -Notification.enableDistributed(isDistributedEnabledCallback); +Notification.isDistributedEnabled(isDistributedEnabledCallback); ``` @@ -2322,6 +2426,8 @@ Sets whether an application supports distributed notifications based on the bund **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Type | Mandatory| Description | @@ -2350,12 +2456,14 @@ Notification.enableDistributedByBundle(bundle, enable, enableDistributedByBundle ## Notification.enableDistributedByBundle8+ -bundleenableDistributedByBundle(bundle: BundleOption, enable: boolean): Promise +bundleenableDistributedByBundle(bundle: BundleOption, enable: boolean): Promise\ Sets whether an application supports distributed notifications based on the bundle. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Type | Mandatory| Description | @@ -2386,6 +2494,8 @@ Obtains whether an application supports distributed notifications based on the b **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Type | Mandatory| Description | @@ -2404,7 +2514,7 @@ var bundle = { bundle: "bundleName1", } -Notification.enableDistributedByBundle(bundle, isDistributedEnabledByBundleCallback); +Notification.isDistributedEnabledByBundle(bundle, isDistributedEnabledByBundleCallback); ``` @@ -2417,6 +2527,8 @@ Obtains whether an application supports distributed notifications based on the b **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Type | Mandatory| Description | @@ -2451,6 +2563,8 @@ Obtains the notification reminder type. This API uses an asynchronous callback t **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Type | Mandatory| Description | @@ -2477,6 +2591,8 @@ Obtains the notification reminder type. This API uses a promise to return the re **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Return value** | Type | Description | @@ -2492,8 +2608,289 @@ Notification.getDeviceRemindType() }); ``` +## Notification.publishAsBundle9+ + +publishAsBundle(request: NotificationRequest, representativeBundle: string, userId: number, callback: AsyncCallback\): void + +Publishes an agent-powered notification. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------- | ---- | --------------------------------------------- | +| request | [NotificationRequest](#notificationrequest) | Yes | Notification to publish.| +| representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | +| userId | number | Yes | ID of the user who receives the notification. | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +// Callback for publishAsBundle +function publishAsBundleCallback(err) { + console.info("==========================>publishAsBundleCallback=======================>"); +} +// Bundle name of the application whose notification function is taken over by the reminder agent +let representativeBundle = "com.example.demo" +// ID of the user who receives the notification +let userId = 100 +// NotificationRequest object +let notificationRequest = { + id: 1, + content: { + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "test_title", + text: "test_text", + additionalText: "test_additionalText" + } + } +} + +Notification.publishAsBundle(notificationRequest, representativeBundle, userId, publishAsBundleCallback); +``` + +## Notification.publishAsBundle9+ + +publishAsBundle(request: NotificationRequest, representativeBundle: string, userId: number): Promise\ + +Publishes a notification through the reminder agent. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------- | ---- | --------------------------------------------- | +| request | [NotificationRequest](#notificationrequest) | Yes | Notification to publish.| +| representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | +| userId | number | Yes | ID of the user who receives the notification. | + +**Example** + +```js +// Bundle name of the application whose notification function is taken over by the reminder agent +let representativeBundle = "com.example.demo" +// ID of the user who receives the notification +let userId = 100 +// NotificationRequest object +var notificationRequest = { + id: 1, + content: { + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "test_title", + text: "test_text", + additionalText: "test_additionalText" + } + } +} + +Notification.publishAsBundle(notificationRequest, representativeBundle, userId).then(() => { + console.info("==========================>publishAsBundleCallback=======================>"); +}); +``` + +## Notification.cancelAsBundle9+ + +cancelAsBundle(id: number, representativeBundle: string, userId: number, callback: AsyncCallback\): void + +Cancels a notification published by the reminder agent. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + + +| Name | Type | Mandatory| Description | +| -------------------- | ------------- | ---- | ------------------------ | +| id | number | Yes | Notification ID. | +| representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | +| userId | number | Yes | ID of the user who receives the notification. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +//cancelAsBundle +function cancelAsBundleCallback(err) { + console.info("==========================>cancelAsBundleCallback=======================>"); +} +// Bundle name of the application whose notification function is taken over by the reminder agent +let representativeBundle = "com.example.demo" +// ID of the user who receives the notification +let userId = 100 + +Notification.cancelAsBundle(0, representativeBundle, userId, cancelAsBundleCallback); +``` + +## Notification.cancelAsBundle9+ + +cancelAsBundle(id: number, representativeBundle: string, userId: number): Promise\ + +Publishes a notification through the reminder agent. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + + +| Name | Type | Mandatory| Description | +| -------------------- | ------ | ---- | ------------------ | +| id | number | Yes | Notification ID. | +| representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent.| +| userId | number | Yes | ID of the user who receives the notification.| + +**Example** + +```js +// Bundle name of the application whose notification function is taken over by the reminder agent +let representativeBundle = "com.example.demo" +// ID of the user who receives the notification +let userId = 100 + +Notification.cancelAsBundle(0, representativeBundle, userId).then(() => { + console.info("==========================>cancelAsBundleCallback=======================>"); +}); +``` + +## Notification.enableNotificationSlot9+ + +enableNotificationSlot(bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback): void + +Sets the enabled status for a notification slot of a specified type. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ---------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| type | [SlotType](#slottype) | Yes | Notification slot type. | +| enable | boolean | Yes | Whether to enable notification. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +//enableNotificationSlot +function enableSlotCallback(err) { + console.log('===================>enableSlotCallback==================>'); +}; + +Notification.enableNotificationSlot( + { bundle: "ohos.samples.notification", }, + notify.SlotType.SOCIAL_COMMUNICATION, + true, + enableSlotCallback); +``` + +## Notification.enableNotificationSlot9+ + +enableNotificationSlot(bundle: BundleOption, type: SlotType, enable: boolean): Promise + +Sets the enabled status for a notification slot of a specified type. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| type | [SlotType](#slottype) | Yes | Notification slot type.| +| enable | boolean | Yes | Whether to enable notification. | + +**Example** + +```js +//enableNotificationSlot +Notification.enableNotificationSlot( + { bundle: "ohos.samples.notification", }, + notify.SlotType.SOCIAL_COMMUNICATION, + true).then(() => { + console.log('====================>enableNotificationSlot====================>'); + }); +``` + +## Notification.isNotificationSlotEnabled9+ + +isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback): void + +Obtains the enabled status of a notification slot of a specified type. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ---------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| type | [SlotType](#slottype) | Yes | Notification slot type. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +//isNotificationSlotEnabled +function getEnableSlotCallback(err, data) { + console.log('===================>getEnableSlotCallback=================='); +}; + +Notification.isNotificationSlotEnabled( + { bundle: "ohos.samples.notification", }, + notify.SlotType.SOCIAL_COMMUNICATION, + getEnableSlotCallback); +``` + +## Notification.isNotificationSlotEnabled9+ + +isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise + +Obtains the enabled status of a notification slot of a specified type. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| type | [SlotType](#slottype) | Yes | Notification slot type.| + +**Example** + +```js +//isNotificationSlotEnabled +Notification.isNotificationSlotEnabled( + { bundle: "ohos.samples.notification", }, + notify.SlotType.SOCIAL_COMMUNICATION, + true).then((data) => { + console.log('====================>isNotificationSlotEnabled====================>'); + }); +``` + ## NotificationSubscriber +**System API**: This is a system API and cannot be called by third-party applications. + ### onConsume onConsume?:(data: [SubscribeCallbackData](#subscribecallbackdata)) @@ -2526,12 +2923,12 @@ function onConsumeCallback(data) { let wantAgent = data.wantAgent; wantAgent .getWant(wantAgent) .then((data1) => { - console.log('===> getWant success want:' + JSON.stringfy(data1)); + console.log('===> getWant success want:' + JSON.stringify(data1)); }) .catch((err) => { - console.error('===> getWant failed because' + JSON.stringfy(err)); + console.error('===> getWant failed because' + JSON.stringify(err)); }); - console.info('===> onConsume callback req.wantAgent:' + JSON.stringfy(req.wantAgent)); + console.info('===> onConsume callback req.wantAgent:' + JSON.stringify(req.wantAgent)); }; var subscriber = { @@ -2766,14 +3163,10 @@ function subscribeCallback(err) { } }; -function onEnabledNotificationChangedCallback(err, callbackData) { - if (err.code) { - console.info("subscribe failed " + JSON.stringify(err)); - } else { - console.info("bundle: ", callbackData.bundle); - console.info("uid: ", callbackData.uid); - console.info("enable: ", callbackData.enable); - } +function onEnabledNotificationChangedCallback(callbackData) { + console.info("bundle: ", callbackData.bundle); + console.info("uid: ", callbackData.uid); + console.info("enable: ", callbackData.enable); }; var subscriber = { @@ -2787,6 +3180,8 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Readable| Writable| Type | Mandatory| Description | | --------------- | ---- | --- | ------------------------------------------------- | ---- | -------- | | request | Yes | No | [NotificationRequest](#notificationrequest) | Yes | Notification content.| @@ -2800,6 +3195,8 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Readable| Writable| Type | Mandatory| Description | | ------ | ---- | --- | ------- | ---- | ---------------- | | bundle | Yes | No | string | Yes | Bundle name of the application. | @@ -2811,6 +3208,8 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Readable| Writable| Type | Description | | ----- | ---- | --- | ------------------------------------- | ------------------------ | | type | Yes | No | [DoNotDisturbType](#donotdisturbtype8) | DND time type.| @@ -2823,13 +3222,14 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. | Name | Value | Description | | ------------ | ---------------- | ------------------------------------------ | -| TYPE_NONE | DoNotDisturbType | Non-DND. | -| TYPE_ONCE | DoNotDisturbType | One-shot DND at the specified time segment (only considering the hour and minute).| -| TYPE_DAILY | DoNotDisturbType | Daily DND at the specified time segment (only considering the hour and minute).| -| TYPE_CLEARLY | DoNotDisturbType | DND at the specified time segment (considering the year, month, day, hour, and minute). | +| TYPE_NONE | 0 | Non-DND. | +| TYPE_ONCE | 1 | One-shot DND at the specified time segment (only considering the hour and minute).| +| TYPE_DAILY | 2 | Daily DND at the specified time segment (only considering the hour and minute).| +| TYPE_CLEARLY | 3 | DND at the specified time segment (considering the year, month, day, hour, and minute). | ## ContentType @@ -2838,11 +3238,11 @@ Notification.subscribe(subscriber, subscribeCallback); | Name | Value | Description | | --------------------------------- | ----------- | ------------------ | -| NOTIFICATION_CONTENT_BASIC_TEXT | ContentType | Normal text notification. | -| NOTIFICATION_CONTENT_LONG_TEXT | ContentType | Long text notification. | -| NOTIFICATION_CONTENT_PICTURE | ContentType | Picture-attached notification. | -| NOTIFICATION_CONTENT_CONVERSATION | ContentType | Conversation notification. | -| NOTIFICATION_CONTENT_MULTILINE | ContentType | Multi-line text notification.| +| NOTIFICATION_CONTENT_BASIC_TEXT | NOTIFICATION_CONTENT_BASIC_TEXT | Normal text notification. | +| NOTIFICATION_CONTENT_LONG_TEXT | NOTIFICATION_CONTENT_LONG_TEXT | Long text notification. | +| NOTIFICATION_CONTENT_PICTURE | NOTIFICATION_CONTENT_PICTURE | Picture-attached notification. | +| NOTIFICATION_CONTENT_CONVERSATION | NOTIFICATION_CONTENT_CONVERSATION | Conversation notification. | +| NOTIFICATION_CONTENT_MULTILINE | NOTIFICATION_CONTENT_MULTILINE | Multi-line text notification.| ## SlotLevel @@ -2850,9 +3250,9 @@ Notification.subscribe(subscriber, subscribeCallback); | Name | Value | Description | | --------------------------------- | ----------- | ------------------ | -| LEVEL_NONE | 0 | The notification feature is disabled. | -| LEVEL_MIN | 1 | The notification feature is enabled, but the notification icon is not displayed in the status bar, with no banner or alert tone.| -| LEVEL_LOW | 2 | The notification feature is enabled, and the notification icon is displayed in the status bar, with no banner or alert tone.| +| LEVEL_NONE | 0 | The notification function is disabled. | +| LEVEL_MIN | 1 | The notification function is enabled, but the notification icon is not displayed in the status bar, with no banner or alert tone.| +| LEVEL_LOW | 2 | The notification function is enabled, and the notification icon is displayed in the status bar, with no banner or alert tone.| | LEVEL_DEFAULT | 3 | The notification feature is enabled, and the notification icon is displayed in the status bar, with an alert tone but no banner.| | LEVEL_HIGH | 4 | The notification feature is enabled, and the notification icon is displayed in the status bar, with an alert tone and banner.| @@ -2884,11 +3284,11 @@ Notification.subscribe(subscriber, subscribeCallback); | Name | Value | Description | | -------------------- | -------- | ---------- | -| UNKNOWN_TYPE | SlotType | Unknown type.| -| SOCIAL_COMMUNICATION | SlotType | Notification slot for social communication.| -| SERVICE_INFORMATION | SlotType | Notification slot for service information.| -| CONTENT_INFORMATION | SlotType | Notification slot for content consultation.| -| OTHER_TYPES | SlotType | Notification slot for other purposes.| +| UNKNOWN_TYPE | 0 | Unknown type.| +| SOCIAL_COMMUNICATION | 1 | Notification slot for social communication.| +| SERVICE_INFORMATION | 2 | Notification slot for service information.| +| CONTENT_INFORMATION | 3 | Notification slot for content consultation.| +| OTHER_TYPES | 0xFFFF | Notification slot for other purposes.| ## NotificationActionButton @@ -2973,6 +3373,8 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Value | Description | | -------------- | --- | --------------------------------- | | TYPE_NONE | 0 | The default flag is used. | @@ -3021,7 +3423,7 @@ Notification.subscribe(subscriber, subscribeCallback); | creatorBundleName | Yes | No | string | No | Name of the bundle that creates the notification. | | creatorUid | Yes | No | number | No | UID used for creating the notification. | | creatorPid | Yes | No | number | No | PID used for creating the notification. | -| creatorUserId8+| Yes | No | number | No | ID of the user who creates a notification. | +| creatorUserId8+| Yes | No | number | No | ID of the user who creates the notification. | | hashCode | Yes | No | string | No | Unique ID of the notification. | | classification | Yes | Yes | string | No | Notification category. | | groupName8+| Yes | Yes | string | No | Group notification name. | @@ -3062,12 +3464,15 @@ Notification.subscribe(subscriber, subscribeCallback); | lightEnabled | Yes | Yes | boolean | No | Whether the indicator blinks for the notification. | | lightColor | Yes | Yes | number | No | Indicator color of the notification. | | vibrationValues | Yes | Yes | Array\ | No | Vibration mode of the notification. | +| enabled9+ | Yes | No | boolean | No | Enabled status of the notification slot. | ## NotificationSorting **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Readable| Writable| Type | Mandatory| Description | | -------- | ---- | --- | ------------------------------------- | ---- | ------------ | | slot | Yes | No | [NotificationSlot](#notificationslot) | Yes | Notification slot content.| @@ -3079,6 +3484,8 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Readable| Writable| Type | Mandatory| Description | | -------------- | ---- | --- | ------------------------------------------------------------ | ---- | ---------------- | | sortings | Yes | No | {[key: string]: [NotificationSorting](#notificationsorting)} | Yes | Array of notification sorting information.| @@ -3089,6 +3496,8 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Readable| Writable| Type | Mandatory| Description | | ----------- | --- | ---- | --------------- | ---- | ------------------------------- | | bundleNames | Yes | Yes | Array\ | No | Bundle names of the applications whose notifications are to be subscribed to.| @@ -3118,6 +3527,8 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Value | Description | | -------------------- | --- | --------------------------------- | | IDLE_DONOT_REMIND | 0 | The device is not in use. No notification is required. | diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index f0e93479b923928923f27bcda147a7c8d23f0d59..bb62764d00730e1abb51a3b302915cd6bee264ca 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -1,6 +1,6 @@ # OS Account Management -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. @@ -48,7 +48,7 @@ Provides methods to manage OS accounts. activateOsAccount(localId: number, callback: AsyncCallback<void>): void -Activates an OS account. This method uses an asynchronous callback to return the result. +Activates an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -76,7 +76,7 @@ This is a system API and cannot be called by third-party applications. activateOsAccount(localId: number): Promise<void> -Activates an OS account. This method uses a promise to return the result. +Activates an OS account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -111,7 +111,7 @@ This is a system API and cannot be called by third-party applications. isMultiOsAccountEnable(callback: AsyncCallback<boolean>): void -Checks whether multiple OS accounts are supported. This method uses an asynchronous callback to return the result. +Checks whether multiple OS accounts are supported. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -135,7 +135,7 @@ Checks whether multiple OS accounts are supported. This method uses an asynchron isMultiOsAccountEnable(): Promise<boolean> -Checks whether multiple OS accounts are supported. This method uses a promise to return the result. +Checks whether multiple OS accounts are supported. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.Account.OsAccount @@ -160,7 +160,7 @@ Checks whether multiple OS accounts are supported. This method uses a promise to isOsAccountActived(localId: number, callback: AsyncCallback<boolean>): void -Checks whether an OS account is activated. This method uses an asynchronous callback to return the result. +Checks whether an OS account is activated. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -188,7 +188,7 @@ Checks whether an OS account is activated. This method uses an asynchronous call isOsAccountActived(localId: number): Promise<boolean> -Checks whether an OS account is activated. This method uses a promise to return the result. +Checks whether an OS account is activated. This API uses a promise to return the result asynchronously. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -222,7 +222,7 @@ Checks whether an OS account is activated. This method uses a promise to return isOsAccountConstraintEnable(localId: number, constraint: string, callback: AsyncCallback<boolean>): void -Checks whether the specified constraint is enabled for an OS account. This method uses an asynchronous callback to return the result. +Checks whether the specified constraint is enabled for an OS account. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -251,7 +251,7 @@ Checks whether the specified constraint is enabled for an OS account. This metho isOsAccountConstraintEnable(localId: number, constraint: string): Promise<boolean> -Checks whether the specified constraint is enabled for an OS account. This method uses a promise to return the result. +Checks whether the specified constraint is enabled for an OS account. This API uses a promise to return the result asynchronously. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -286,7 +286,7 @@ Checks whether the specified constraint is enabled for an OS account. This metho isTestOsAccount(callback: AsyncCallback<boolean>): void -Checks whether this OS account is a test account. This method uses an asynchronous callback to return the result. +Checks whether this OS account is a test account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -310,7 +310,7 @@ Checks whether this OS account is a test account. This method uses an asynchrono isTestOsAccount(): Promise<boolean> -Checks whether this OS account is a test account. This method uses a promise to return the result. +Checks whether this OS account is a test account. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.Account.OsAccount @@ -335,7 +335,7 @@ Checks whether this OS account is a test account. This method uses a promise to isOsAccountVerified(callback: AsyncCallback<boolean>): void -Checks whether this OS account has been verified. This method uses an asynchronous callback to return the result. +Checks whether this OS account has been verified. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -359,7 +359,7 @@ Checks whether this OS account has been verified. This method uses an asynchrono isOsAccountVerified(localId: number, callback: AsyncCallback<boolean>): void -Checks whether an OS account has been verified. This method uses an asynchronous callback to return the result. +Checks whether an OS account has been verified. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -386,7 +386,7 @@ Checks whether an OS account has been verified. This method uses an asynchronous isOsAccountVerified(localId?: number): Promise<boolean> -Checks whether an OS account has been verified. This method uses a promise to return the result. +Checks whether an OS account has been verified. This API uses a promise to return the result asynchronously. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -419,7 +419,7 @@ Checks whether an OS account has been verified. This method uses a promise to re removeOsAccount(localId: number, callback: AsyncCallback<void>): void -Removes an OS account. This method uses an asynchronous callback to return the result. +Removes an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -451,7 +451,7 @@ This is a system API and cannot be called by third-party applications. removeOsAccount(localId: number): Promise<void> -Removes an OS account. This method uses a promise to return the result. +Removes an OS account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -491,7 +491,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountConstraints(localId: number, constraints: Array<string>, enable: boolean,callback: AsyncCallback<void>): void -Sets or removes constraints for an OS account. This method uses an asynchronous callback to return the result. +Sets or removes constraints for an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -522,7 +522,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountConstraints(localId: number, constraints: Array<string>, enable: boolean): Promise<void> -Sets or removes constraints for an OS account. This method uses a promise to return the result. +Sets or removes constraints for an OS account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -560,7 +560,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountName(localId: number, localName: string, callback: AsyncCallback<void>): void -Sets a name for an OS account. This method uses an asynchronous callback to return the result. +Sets a name for an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -591,7 +591,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountName(localId: number, localName: string): Promise<void> -Sets a name for an OS account. This method uses a promise to return the result. +Sets a name for an OS account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -629,7 +629,7 @@ This is a system API and cannot be called by third-party applications. getCreatedOsAccountsCount(callback: AsyncCallback<number>): void -Obtains the number of OS accounts created. This method uses an asynchronous callback to return the result. +Obtains the number of OS accounts created. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -655,7 +655,7 @@ Obtains the number of OS accounts created. This method uses an asynchronous call getCreatedOsAccountsCount(): Promise<number> -Obtains the number of OS accounts created. This method uses a promise to return the result. +Obtains the number of OS accounts created. This API uses a promise to return the result asynchronously. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -682,7 +682,7 @@ Obtains the number of OS accounts created. This method uses a promise to return getOsAccountLocalIdFromProcess(callback: AsyncCallback<number>): void -Obtains the ID of the OS account to which the current process belongs. This method uses an asynchronous callback to return the result. +Obtains the ID of the OS account to which the current process belongs. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -706,7 +706,7 @@ Obtains the ID of the OS account to which the current process belongs. This meth getOsAccountLocalIdFromProcess(): Promise<number> -Obtains the ID of the OS account to which the current process belongs. This method uses a promise to return the result. +Obtains the ID of the OS account to which the current process belongs. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.Account.OsAccount @@ -731,7 +731,7 @@ Obtains the ID of the OS account to which the current process belongs. This meth getOsAccountLocalIdFromUid(uid: number, callback: AsyncCallback<number>): void -Obtains the OS account ID based on the process UID. This method uses an asynchronous callback to return the result. +Obtains the OS account ID based on the process UID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -757,7 +757,7 @@ Obtains the OS account ID based on the process UID. This method uses an asynchro getOsAccountLocalIdFromUid(uid: number): Promise<number> -Obtains the OS account ID based on the process UID. This method uses a promise to return the result. +Obtains the OS account ID based on the process UID. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.Account.OsAccount @@ -789,7 +789,7 @@ Obtains the OS account ID based on the process UID. This method uses a promise t getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo, callback: AsyncCallback<number>): void -Obtains the OS account ID based on domain account information. This method uses an asynchronous callback to return the result. +Obtains the OS account ID based on domain account information. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -817,7 +817,7 @@ Obtains the OS account ID based on domain account information. This method uses getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo): Promise<number> -Obtains the OS account ID based on domain account information. This method uses a promise to return the result. +Obtains the OS account ID based on domain account information. This API uses a promise to return the result asynchronously. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -851,7 +851,7 @@ Obtains the OS account ID based on domain account information. This method uses queryMaxOsAccountNumber(callback: AsyncCallback<number>): void -Obtains the maximum number of OS accounts that can be created. This method uses an asynchronous callback to return the result. +Obtains the maximum number of OS accounts that can be created. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -877,7 +877,7 @@ This is a system API and cannot be called by third-party applications. queryMaxOsAccountNumber(): Promise<number> -Obtains the maximum number of OS accounts that can be created. This method uses a promise to return the result. +Obtains the maximum number of OS accounts that can be created. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -904,7 +904,7 @@ This is a system API and cannot be called by third-party applications. getOsAccountAllConstraints(localId: number, callback: AsyncCallback<Array<string>>): void -Obtains all constraints enabled for an OS account. This method uses an asynchronous callback to return the result. +Obtains all constraints enabled for an OS account. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -932,7 +932,7 @@ Obtains all constraints enabled for an OS account. This method uses an asynchron getOsAccountAllConstraints(localId: number): Promise<Array<string>> -Obtains all constraints enabled for an OS account. This method uses a promise to return the result. +Obtains all constraints enabled for an OS account. This API uses a promise to return the result asynchronously. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -966,7 +966,7 @@ Obtains all constraints enabled for an OS account. This method uses a promise to queryAllCreatedOsAccounts(callback: AsyncCallback<Array<OsAccountInfo>>): void -Obtains information about all the OS accounts created. This method uses an asynchronous callback to return the result. +Obtains information about all the OS accounts created. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -992,7 +992,7 @@ This is a system API and cannot be called by third-party applications. queryAllCreatedOsAccounts(): Promise<Array<OsAccountInfo>> -Obtains information about all the OS accounts created. This method uses a promise to return the result. +Obtains information about all the OS accounts created. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -1019,7 +1019,7 @@ This is a system API and cannot be called by third-party applications. queryActivatedOsAccountIds(callback: AsyncCallback<Array<number>>): void -Obtains information about all activated OS accounts. This method uses an asynchronous callback to return the result. +Obtains information about all activated OS accounts. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1046,7 +1046,7 @@ Obtains information about all activated OS accounts. This method uses an asynchr queryActivatedOsAccountIds(): Promise<Array<number>> -Obtains information about all activated OS accounts. This method uses a promise to return the result. +Obtains information about all activated OS accounts. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.Account.OsAccount @@ -1071,7 +1071,7 @@ Obtains information about all activated OS accounts. This method uses a promise createOsAccount(localName: string, type: OsAccountType, callback: AsyncCallback<OsAccountInfo>): void -Creates an OS account. This method uses an asynchronous callback to return the result. +Creates an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1101,7 +1101,7 @@ This is a system API and cannot be called by third-party applications. createOsAccount(localName: string, type: OsAccountType): Promise<OsAccountInfo> -Creates an OS account. This method uses a promise to return the result. +Creates an OS account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -1137,7 +1137,7 @@ This is a system API and cannot be called by third-party applications. createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo, callback: AsyncCallback<OsAccountInfo>): void -Creates an OS account and associates it with the specified domain account. This method uses an asynchronous callback to return the result. +Creates an OS account and associates it with the specified domain account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1168,7 +1168,7 @@ This is a system API and cannot be called by third-party applications. createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo): Promise<OsAccountInfo> -Creates an OS account and associates it with the specified domain account. This method uses a promise to return the result. +Creates an OS account and associates it with the specified domain account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -1205,7 +1205,7 @@ This is a system API and cannot be called by third-party applications. queryCurrentOsAccount(callback: AsyncCallback<OsAccountInfo>): void -Obtains information about the OS account to which the current process belongs. This method uses an asynchronous callback to return the result. +Obtains information about the OS account to which the current process belongs. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1231,7 +1231,7 @@ Obtains information about the OS account to which the current process belongs. T queryCurrentOsAccount(): Promise<OsAccountInfo> -Obtains information about the OS account to which the current process belongs. This method uses a promise to return the result. +Obtains information about the OS account to which the current process belongs. This API uses a promise to return the result asynchronously. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1258,7 +1258,7 @@ Obtains information about the OS account to which the current process belongs. T queryOsAccountById(localId: number, callback: AsyncCallback<OsAccountInfo>): void -Obtains information about an OS account. This method uses an asynchronous callback to return the result. +Obtains information about an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1288,7 +1288,7 @@ This is a system API and cannot be called by third-party applications. queryOsAccountById(localId: number): Promise<OsAccountInfo> -Obtains information about an OS account. This method uses a promise to return the result. +Obtains information about an OS account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -1324,7 +1324,7 @@ This is a system API and cannot be called by third-party applications. getOsAccountTypeFromProcess(callback: AsyncCallback<OsAccountType>): void -Obtains the type of the OS account to which the current process belongs. This method uses an asynchronous callback to return the result. +Obtains the type of the OS account to which the current process belongs. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1348,7 +1348,7 @@ Obtains the type of the OS account to which the current process belongs. This me getOsAccountTypeFromProcess(): Promise<OsAccountType> -Obtains the type of the OS account to which the current process belongs. This method uses a promise to return the result. +Obtains the type of the OS account to which the current process belongs. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.Account.OsAccount @@ -1373,7 +1373,7 @@ Obtains the type of the OS account to which the current process belongs. This me getDistributedVirtualDeviceId(callback: AsyncCallback<string>): void -Obtains the ID of this distributed virtual device. This method uses an asynchronous callback to return the result. +Obtains the ID of this distributed virtual device. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC or ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1399,7 +1399,7 @@ Obtains the ID of this distributed virtual device. This method uses an asynchron getDistributedVirtualDeviceId(): Promise<string> -Obtains the ID of this distributed virtual device. This method uses a promise to return the result. +Obtains the ID of this distributed virtual device. This API uses a promise to return the result asynchronously. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC or ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1426,7 +1426,7 @@ Obtains the ID of this distributed virtual device. This method uses a promise to getOsAccountProfilePhoto(localId: number, callback: AsyncCallback<string>): void -Obtains the profile photo of an OS account. This method uses an asynchronous callback to return the result. +Obtains the profile photo of an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1456,7 +1456,7 @@ This is a system API and cannot be called by third-party applications. getOsAccountProfilePhoto(localId: number): Promise<string> -Obtains the profile photo of an OS account. This method uses a promise to return the result. +Obtains the profile photo of an OS account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -1492,7 +1492,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountProfilePhoto(localId: number, photo: string, callback: AsyncCallback<void>): void -Sets a profile photo for an OS account. This method uses an asynchronous callback to return the result. +Sets a profile photo for an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1526,7 +1526,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountProfilePhoto(localId: number, photo: string): Promise<void> -Sets a profile photo for an OS account. This method uses a promise to return the result. +Sets a profile photo for an OS account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -1567,7 +1567,7 @@ This is a system API and cannot be called by third-party applications. getOsAccountLocalIdBySerialNumber(serialNumber: number, callback: AsyncCallback<number>): void -Obtains the OS account ID based on the SN. This method uses an asynchronous callback to return the result. +Obtains the OS account ID based on the SN. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1593,7 +1593,7 @@ Obtains the OS account ID based on the SN. This method uses an asynchronous call getOsAccountLocalIdBySerialNumber(serialNumber: number): Promise<number> -Obtains the OS account ID based on the SN. This method uses a promise to return the result. +Obtains the OS account ID based on the SN. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.Account.OsAccount @@ -1625,7 +1625,7 @@ Obtains the OS account ID based on the SN. This method uses a promise to return getSerialNumberByOsAccountLocalId(localId: number, callback: AsyncCallback<number>): void -Obtains the SN of an OS account based on the account ID. This method uses an asynchronous callback to return the result. +Obtains the SN of an OS account based on the account ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1651,7 +1651,7 @@ Obtains the SN of an OS account based on the account ID. This method uses an asy getSerialNumberByOsAccountLocalId(localId: number): Promise<number> -Obtains the SN of an OS account based on the account ID. This method uses a promise to return the result. +Obtains the SN of an OS account based on the account ID. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.Account.OsAccount @@ -1683,7 +1683,7 @@ Obtains the SN of an OS account based on the account ID. This method uses a prom on(type: 'activate' | 'activating', name: string, callback: Callback<number>): void -Subscribes to OS account changes. This method uses an asynchronous callback to return the result. +Subscribes to OS account changes. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1713,7 +1713,7 @@ This is a system API and cannot be called by third-party applications. off(type: 'activate' | 'activating', name: string, callback?: Callback<number>): void -Unsubscribes from the OS account changes. This method uses an asynchronous callback to return the result. +Unsubscribes from the OS account changes. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1739,6 +1739,173 @@ This is a system API and cannot be called by third-party applications. accountManager.off("activating", "osAccountOnOffNameA", offCallback); ``` +### getBundleIdFromUid9+ + +getBundleIdFromUid(uid: number, callback: AsyncCallback<number>): void; + +Obtains the bundle ID based on the UID. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ------------------------------------------------------------ | +| uid | number | Yes | Process UID.| +| callback | AsyncCallback<number> | Yes | Callback used to return the bundle ID obtained. | + +**Example** + + ```js + var testUid = 1000000; + osAccountManager.getBundleIdFromUid(testUid,(err,bundleId)=>{ + console.info("getBundleIdFromUid errInfo:" + JSON.stringify(err)); + console.info("getBundleIdFromUid bundleId:" + JSON.stringify(bundleId)); + }); + ``` +### getBundleIdFromUid9+ + +getBundleIdFromUid(uid: number): Promise<number>; + +Obtains the bundle ID based on the UID. This API uses a promise to return the result asynchronously. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------ | +| uid | number | Yes | Process UID.| + +**Return Value** + +| Type | Description | +| :-------------------- | :----------------------------------------------------------- | +| Promise<number> | Promise used to return the bundle ID obtained.| + +**Example** + + ```js + var testUid = 1000000; + var bundleIdInfo = await osAccountManager.getBundleIdFromUid(testUid).catch((err)=>{ + console.info("getBundleIdFromUid errInfo:" + JSON.stringify(err));}) + console.info("getBundleIdFromUid bundleId:" + JSON.stringify(bundleIdInfo)); + ``` + +### isMainOsAccount9+ + +isMainOsAccount(callback: AsyncCallback<boolean>): void; + +Checks whether the current process belongs to the main OS account. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the current process belongs to the main OS account, **true** will be returned. Otherwise, **false** will be returned. | + +**Example** + + ```js + osAccountManager.isMainOsAccount((err,result)=>{ + console.info("isMainOsAccount errInfo:" + JSON.stringify(err)); + console.info("isMainOsAccount result:" + JSON.stringify(result)); + }); + ``` +### isMainOsAccount9+ + +isMainOsAccount(): Promise<boolean>; + +Checks whether the current process belongs to the main OS account. This API uses a promise to return the result asynchronously. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Return Value** + +| Type | Description | +| :-------------------- | :----------------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. If the current process belongs to the main OS account, **true** will be returned. Otherwise, **false** will be returned.| + +**Example** + + ```js + var result = await osAccountManager.isMainOsAccount().catch((err)=>{ + console.info("isMainOsAccount errInfo:" + JSON.stringify(err)); + }); + console.info("isMainOsAccount result:" + JSON.stringify(result)); + ``` +### queryOsAccountConstraintSourceTypes9+ + +queryOsAccountConstraintSourceTypes(localId: number, constraint: string, callback: AsyncCallback<Array<ConstraintSourceTypeInfo>>): void; + +Obtains the constraint source information of an OS account. + +This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ------------------------------------------------------------ | +| localId | number | Yes | ID of the target OS account.| +| constraint | string | Yes | Name of the [constraint](#constraints) to query.| +| callback | AsyncCallback<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Yes | Callback used to return the source information about the specified [constraint] (#constraints). | + +**Example** + + ```js + osAccountManager.queryOsAccountConstraintSourceTypes(100, "constraint.wifi",(err,sourceTypeInfos)=>{ + console.info("queryOsAccountConstraintSourceType errInfo:" + JSON.stringify(err)); + console.info("queryOsAccountConstraintSourceType sourceTypeInfos:" + JSON.stringify(sourceTypeInfos)); + }); + ``` + +### queryOsAccountConstraintSourceTypes9+ + +queryOsAccountConstraintSourceTypes(localId: number, constraint: string): Promise<Array<ConstraintSourceTypeInfo>>; + +Obtains the constraint source information of an OS account. This API uses a promise to return the result asynchronously. + +This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------ | +| localId | number | Yes | ID of the target OS account.| +| constraint | string | Yes | Name of the [constraint](#constraints) to query.| + +**Return Value** + +| Type | Description | +| :-------------------- | :----------------------------------------------------------- | +| Promise<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Promise used to return the source information about the specified [constraint] (#constraints).| + +**Example** + + ```js + var sourceTypeInfos = await osAccountManager.queryOsAccountConstraintSourceTypes(100, "constraint.wifi").catch((err)=>{ + console.info("queryOsAccountConstraintSourceType errInfo:" + JSON.stringify(err));}) + console.info("queryOsAccountConstraintSourceType sourceTypeInfos:" + JSON.stringify(sourceTypeInfos)); + ``` + ## OsAccountInfo Defines information about an OS account. @@ -1839,3 +2006,27 @@ Domain account information. | constraint.screen.timeout.set | A user is not allowed to configure the screen off timeout.| | constraint.print | A user is not allowed to print.| | constraint.private.dns.set | A user is not allowed to configure a private domain name server (DNS).| + +## ConstraintSourceTypeInfo9+ + +Defines information about the source of a constraint. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ---------- | +| localId | number | Yes | ID of the OS account. | +| type | [ConstraintSourceType](#constraintsourcetype) | Yes | Type of the constrain source.| + +## ConstraintSourceType9+ + +Enumerates the constraint sources. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ------ | ------ | ------------ | +| CONSTRAINT_NOT_EXIST | 0 | The constraint does not exist.| +| CONSTRAINT_TYPE_BASE | 1 | Constraint from system settings. | +| CONSTRAINT_TYPE_DEVICE_OWNER | 2 | Constraint from the device owners' settings. | +| CONSTRAINT_TYPE_PROFILE_OWNER | 3 | Constraint from the profile owners' settings. | diff --git a/en/application-dev/reference/apis/js-apis-pasteboard.md b/en/application-dev/reference/apis/js-apis-pasteboard.md index c5ca90fd33c1de4b2eb4f4fff33eee5e2d899a79..cf7fbb1caa02a7c9c8f6b434a227a3275574fa6c 100644 --- a/en/application-dev/reference/apis/js-apis-pasteboard.md +++ b/en/application-dev/reference/apis/js-apis-pasteboard.md @@ -1,7 +1,7 @@ # Pasteboard -> ![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. +> **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. > @@ -48,9 +48,9 @@ Creates a **PasteData** object for plain text. **Example** -```js -var pasteData = pasteboard.createPlainTextData("content"); -``` + ```js + var pasteData = pasteboard.createPlainTextData("content"); + ``` ## pasteboard.createHtmlData7+ @@ -75,10 +75,10 @@ Creates a **PasteData** object for HTML text. **Example** -```js -var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; -var pasteData = pasteboard.createHtmlData(html); -``` + ```js + var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; + var pasteData = pasteboard.createHtmlData(html); + ``` ## pasteboard.createWantData7+ @@ -103,13 +103,13 @@ Creates a **PasteData** object for Want text. **Example** -```js -var object = { - bundleName: "com.example.aafwk.test", - abilityName: "com.example.aafwk.test.TwoAbility" -}; -var pasteData = pasteboard.createWantData(object); -``` + ```js + var object = { + bundleName: "com.example.aafwk.test", + abilityName: "com.example.aafwk.test.TwoAbility" + }; + var pasteData = pasteboard.createWantData(object); + ``` ## pasteboard.createUriData7+ @@ -134,9 +134,9 @@ Creates a **PasteData** object for URI text. **Example** -```js -var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1?user.txt"); -``` + ```js + var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1?user.txt"); + ``` ## pasteboard.createPlainTextRecord7+ @@ -161,9 +161,9 @@ Creates a **PasteDataRecord** object of the plain text type. **Example** -```js -var record = pasteboard.createPlainTextRecord("hello"); -``` + ```js + var record = pasteboard.createPlainTextRecord("hello"); + ``` ## pasteboard.createHtmlTextRecord7+ @@ -188,10 +188,10 @@ Creates a **PasteDataRecord** object of the HTML text type. **Example** -```js -var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; -var record = pasteboard.createHtmlTextRecord(html); -``` + ```js + var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; + var record = pasteboard.createHtmlTextRecord(html); + ``` ## pasteboard.createWantRecord7+ @@ -216,13 +216,13 @@ Creates a **PasteDataRecord** object of the Want text type. **Example** -```js -var object = { - bundleName: "com.example.aafwk.test", - abilityName: "com.example.aafwk.test.TwoAbility" -}; -var record = pasteboard.createWantRecord(object); -``` + ```js + var object = { + bundleName: "com.example.aafwk.test", + abilityName: "com.example.aafwk.test.TwoAbility" + }; + var record = pasteboard.createWantRecord(object); + ``` ## pasteboard.createUriRecord7+ @@ -247,9 +247,9 @@ Creates a **PasteDataRecord** object of the URI text type. **Example** -```js -var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1?user.txt"); -``` + ```js + var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1?user.txt"); + ``` ## PasteDataProperty7+ @@ -301,14 +301,14 @@ Forcibly converts the content in this **PasteData** object to the plain text. Th **Example** -```js -var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1?user.txt"); -record.convertToText().then((data) => { - console.info('convertToText success data : ' + JSON.stringify(data)); -}).catch((error) => { - console.error('convertToText failed because ' + JSON.stringify(error)); -}); -``` + ```js + var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1?user.txt"); + record.convertToText().then((data) => { + console.info('convertToText success data : ' + JSON.stringify(data)); + }).catch((error) => { + console.error('convertToText failed because ' + JSON.stringify(error)); + }); + ``` ### convertToText7+ @@ -327,16 +327,16 @@ Forcibly converts the content in this **PasteData** object to the plain text. Th **Example** -```js -var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1?user.txt"); -record.convertToText((err, data) => { - if (err) { - console.error('convertToText failed because ' + JSON.stringify(err)); - return; - } - console.info('convertToText success data : ' + JSON.stringify(data)); -}); -``` + ```js + var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1?user.txt"); + record.convertToText((err, data) => { + if (err) { + console.error('convertToText failed because ' + JSON.stringify(err)); + return; + } + console.info('convertToText success data : ' + JSON.stringify(data)); + }); + ``` ## PasteData @@ -366,10 +366,10 @@ Obtains the plain text of the primary record. **Example** -```js -var pasteData = pasteboard.createPlainTextData("hello"); -var plainText = pasteData.getPrimaryText(); -``` + ```js + var pasteData = pasteboard.createPlainTextData("hello"); + var plainText = pasteData.getPrimaryText(); + ``` ### getPrimaryHtml7+ @@ -388,11 +388,11 @@ Obtains the HTML text of the primary record. **Example** -```js -var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; -var pasteData = pasteboard.createHtmlData(html); -var htmlText = pasteData.getPrimaryHtml(); -``` + ```js + var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; + var pasteData = pasteboard.createHtmlData(html); + var htmlText = pasteData.getPrimaryHtml(); + ``` ### getPrimaryWant7+ @@ -411,14 +411,14 @@ Obtains the **Want** object of the primary record. **Example** -```js -var object = { - bundleName: "com.example.aafwk.test", - abilityName: "com.example.aafwk.test.TwoAbility" -}; -var pasteData = pasteboard.createWantData(object); -var want = pasteData.getPrimaryWant(); -``` + ```js + var object = { + bundleName: "com.example.aafwk.test", + abilityName: "com.example.aafwk.test.TwoAbility" + }; + var pasteData = pasteboard.createWantData(object); + var want = pasteData.getPrimaryWant(); + ``` ### getPrimaryUri7+ @@ -437,10 +437,10 @@ Obtains the URI text of the primary record. **Example** -```js -var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1?user.txt"); -var uri = pasteData.getPrimaryUri(); -``` + ```js + var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1?user.txt"); + var uri = pasteData.getPrimaryUri(); + ``` ### addTextRecord7+ @@ -485,11 +485,11 @@ The pasteboard supports a maximum number of 128 data records. **Example** -```js -var pasteData = pasteboard.createPlainTextData("hello"); -var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; -pasteData.addHtmlRecord(html); -``` + ```js + var pasteData = pasteboard.createPlainTextData("hello"); + var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; + pasteData.addHtmlRecord(html); + ``` ### addWantRecord7+ @@ -510,14 +510,14 @@ The pasteboard supports a maximum number of 128 data records. **Example** -```js -var pasteData = pasteboard.createPlainTextData("hello"); -var object = { - bundleName: "com.example.aafwk.test", - abilityName: "com.example.aafwk.test.TwoAbility" -}; -pasteData.addWantRecord(object); -``` + ```js + var pasteData = pasteboard.createPlainTextData("hello"); + var object = { + bundleName: "com.example.aafwk.test", + abilityName: "com.example.aafwk.test.TwoAbility" + }; + pasteData.addWantRecord(object); + ``` ### addUriRecord7+ @@ -538,10 +538,10 @@ The pasteboard supports a maximum number of 128 data records. **Example** -```js -var pasteData = pasteboard.createPlainTextData("hello"); -pasteData.addUriRecord("dataability:///com.example.myapplication1?user.txt"); -``` + ```js + var pasteData = pasteboard.createPlainTextData("hello"); + pasteData.addUriRecord("dataability:///com.example.myapplication1?user.txt"); + ``` ### addRecord7+ @@ -562,14 +562,14 @@ The pasteboard supports a maximum number of 128 data records. **Example** -```js -var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1?user.txt"); -var textRecord = pasteboard.createPlainTextRecord("hello"); -var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; -var htmlRecord = pasteboard.createHtmlTextRecord(html); -pasteData.addRecord(textRecord); -pasteData.addRecord(htmlRecord); -``` + ```js + var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1?user.txt"); + var textRecord = pasteboard.createPlainTextRecord("hello"); + var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; + var htmlRecord = pasteboard.createHtmlTextRecord(html); + pasteData.addRecord(textRecord); + pasteData.addRecord(htmlRecord); + ``` ### getMimeTypes7+ @@ -588,10 +588,10 @@ Obtains **mimeTypes** in [PasteDataProperty](#pastedataproperty7) from this past **Example** -```js -var pasteData = pasteboard.createPlainTextData("hello"); -var types = pasteData.getMimeTypes(); -``` + ```js + var pasteData = pasteboard.createPlainTextData("hello"); + var types = pasteData.getMimeTypes(); + ``` ### getPrimaryMimeType7+ @@ -610,10 +610,10 @@ Obtains the data type of the primary record. **Example** -```js -var pasteData = pasteboard.createPlainTextData("hello"); -var type = pasteData.getPrimaryMimeType(); -``` + ```js + var pasteData = pasteboard.createPlainTextData("hello"); + var type = pasteData.getPrimaryMimeType(); + ``` ### getProperty7+ @@ -632,10 +632,10 @@ Obtains the property description object. **Example** -```js -var pasteData = pasteboard.createPlainTextData("hello"); -var property = pasteData.getProperty(); -``` + ```js + var pasteData = pasteboard.createPlainTextData("hello"); + var property = pasteData.getProperty(); + ``` ### getRecordAt7+ @@ -660,10 +660,10 @@ Obtains the record with the specified index. **Example** -```js -var pasteData = pasteboard.createPlainTextData("hello"); -var record = pasteData.getRecordAt(0); -``` + ```js + var pasteData = pasteboard.createPlainTextData("hello"); + var record = pasteData.getRecordAt(0); + ``` ### getRecordCount7+ @@ -682,10 +682,10 @@ Obtains the number of data records in this pasteboard. **Example** -```js -var pasteData = pasteboard.createPlainTextData("hello"); -var count = pasteData.getRecordCount(); -``` + ```js + var pasteData = pasteboard.createPlainTextData("hello"); + var count = pasteData.getRecordCount(); + ``` ### getTag7+ @@ -704,10 +704,10 @@ Obtains the user-defined tag content. If the tag content is not set, null is ret **Example** -```js -var pasteData = pasteboard.createPlainTextData("hello"); -var tag = pasteData.getTag(); -``` + ```js + var pasteData = pasteboard.createPlainTextData("hello"); + var tag = pasteData.getTag(); + ``` ### hasMimeType7+ @@ -732,10 +732,10 @@ Checks whether the content of this pasteboard contains the specified data type. **Example** -```js -var pasteData = pasteboard.createPlainTextData("hello"); -var hasType = pasteData.hasMimeType(pasteboard.MIMETYPE_TEXT_PLAIN); -``` + ```js + var pasteData = pasteboard.createPlainTextData("hello"); + var hasType = pasteData.hasMimeType(pasteboard.MIMETYPE_TEXT_PLAIN); + ``` ### removeRecordAt7+ @@ -760,10 +760,10 @@ Removes the data record with a specified index from this pasteboard. **Example** -```js -var pasteData = pasteboard.createPlainTextData("hello"); -var isRemove = pasteData.removeRecordAt(0); -``` + ```js + var pasteData = pasteboard.createPlainTextData("hello"); + var isRemove = pasteData.removeRecordAt(0); + ``` ### replaceRecordAt7+ @@ -789,11 +789,11 @@ Replaces the data record with a specified index in this pasteboard. **Example** -```js -var pasteData = pasteboard.createPlainTextData("hello"); -var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1?user.txt"); -var isReplace = pasteData.replaceRecordAt(0, record); -``` + ```js + var pasteData = pasteboard.createPlainTextData("hello"); + var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1?user.txt"); + var isReplace = pasteData.replaceRecordAt(0, record); + ``` ## pasteboard.getSystemPasteboard @@ -812,9 +812,9 @@ Obtains the system pasteboard. **Example** -```js -var systemPasteboard = pasteboard.getSystemPasteboard(); -``` + ```js + var systemPasteboard = pasteboard.getSystemPasteboard(); + ``` ## SystemPasteboard @@ -843,17 +843,17 @@ Writes data to a pasteboard. This API uses an asynchronous callback to return th **Example** -```js -var pasteData = pasteboard.createPlainTextData("content"); -var systemPasteboard = pasteboard.getSystemPasteboard(); -systemPasteboard.setPasteData(pasteData, (error, data) => { - if (error) { - console.error('Failed to setPasteData. Cause: ' + error.message); - return; - } - console.info('setPasteData successfully.'); -}); -``` + ```js + var pasteData = pasteboard.createPlainTextData("content"); + var systemPasteboard = pasteboard.getSystemPasteboard(); + systemPasteboard.setPasteData(pasteData, (error, data) => { + if (error) { + console.error('Failed to setPasteData. Cause: ' + error.message); + return; + } + console.info('setPasteData successfully.'); + }); + ``` ### setPasteData @@ -878,15 +878,15 @@ Writes data to a pasteboard. This API uses a promise to return the result. **Example** -```js -var pasteData = pasteboard.createPlainTextData("content"); -var systemPasteboard = pasteboard.getSystemPasteboard(); -systemPasteboard.setPasteData(pasteData).then((data) => { - console.info('setPasteData success.'); -}).catch((error) => { - console.error('Failed to setPasteData. Cause: ' + error.message); -}); -``` + ```js + var pasteData = pasteboard.createPlainTextData("content"); + var systemPasteboard = pasteboard.getSystemPasteboard(); + systemPasteboard.setPasteData(pasteData).then((data) => { + console.info('setPasteData success.'); + }).catch((error) => { + console.error('Failed to setPasteData. Cause: ' + error.message); + }); + ``` ### getPasteData @@ -905,16 +905,16 @@ Reads the system pasteboard content. This API uses an asynchronous callback to r **Example** -```js -var systemPasteboard = pasteboard.getSystemPasteboard(); -systemPasteboard.getPasteData((error, pasteData) => { - if (error) { - console.error('Failed to getPasteData. Cause: ' + error.message); - return; - } - var text = pasteData.getPrimaryText(); -}); -``` + ```js + var systemPasteboard = pasteboard.getSystemPasteboard(); + systemPasteboard.getPasteData((error, pasteData) => { + if (error) { + console.error('Failed to getPasteData. Cause: ' + error.message); + return; + } + var text = pasteData.getPrimaryText(); + }); + ``` ### getPasteData @@ -933,14 +933,14 @@ Reads the system pasteboard content. This API uses a promise to return the resul **Example** -```js -var systemPasteboard = pasteboard.getSystemPasteboard(); -systemPasteboard.getPasteData().then((pasteData) => { - var text = pasteData.getPrimaryText(); -}).catch((error) => { - console.error('Failed to getPasteData. Cause: ' + error.message); -}) -``` + ```js + var systemPasteboard = pasteboard.getSystemPasteboard(); + systemPasteboard.getPasteData().then((pasteData) => { + var text = pasteData.getPrimaryText(); + }).catch((error) => { + console.error('Failed to getPasteData. Cause: ' + error.message); + }) + ``` ### on('update')7+ @@ -960,18 +960,18 @@ Subscribes to the content change event of the system pasteboard. If the pasteboa **Example** -```js -var systemPasteboard = pasteboard.getSystemPasteboard(); -var listener = ()=>{ - console.info('The system pasteboard has changed'); -}; -systemPasteboard.on('update', listener); -``` + ```js + var systemPasteboard = pasteboard.getSystemPasteboard(); + var listener = () => { + console.info('The system pasteboard has changed'); + }; + systemPasteboard.on('update', listener); + ``` ### off('update')7+ -off(type: 'update', callback? : () =>void ): void +off(type: 'update', callback?: () =>void ): void Unsubscribes from the system pasteboard content change event. @@ -986,9 +986,12 @@ Unsubscribes from the system pasteboard content change event. **Example** -```js -systemPasteboard.off('update', listener); -``` + ```js + let listener = () => { + console.info('The system pasteboard has changed'); + }; + systemPasteboard.off('update', listener); + ``` ### hasPasteData7+ @@ -1007,15 +1010,15 @@ Checks whether the system pasteboard contains content. This API uses an asynchro **Example** -```js -systemPasteboard.hasPasteData((err, data) => { - if (err) { - console.error('failed to hasPasteData because ' + JSON.stringify(err)); - return; - } - console.info('success hasPasteData : ' + JSON.stringify(data)); -}); -``` + ```js + systemPasteboard.hasPasteData((err, data) => { + if (err) { + console.error('failed to hasPasteData because ' + JSON.stringify(err)); + return; + } + console.info('success hasPasteData : ' + JSON.stringify(data)); + }); + ``` ### hasPasteData7+ @@ -1059,15 +1062,15 @@ Clears the system pasteboard content. This API uses an asynchronous callback to **Example** -```js -systemPasteboard.clear((err, data) => { - if (err) { - console.error('failed to clear because ' + JSON.stringify(err)); - return; - } - console.info('success clear'); -}); -``` + ```js + systemPasteboard.clear((err, data) => { + if (err) { + console.error('failed to clear because ' + JSON.stringify(err)); + return; + } + console.info('success clear'); + }); + ``` ### clear7+ @@ -1086,10 +1089,10 @@ Clears the system pasteboard content. This API uses a promise to return the resu **Example** -```js -systemPasteboard.clear().then((data) => { - console.info('success clear'); -}).catch((error) => { - console.error('failed to clear because ' + JSON.stringify(error)); -}); -``` \ No newline at end of file + ```js + systemPasteboard.clear().then((data) => { + console.info('success clear'); + }).catch((error) => { + console.error('failed to clear because ' + JSON.stringify(error)); + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md index 0246c42771b96cf5db8594eb19234cfe7a4f9a44..de7be38f0c910c202f90c0eb76396e18f4f5fd7e 100644 --- a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md +++ b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md @@ -3,7 +3,6 @@ > **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. - Provides the permission request result. ## Modules to Import @@ -12,6 +11,29 @@ Provides the permission request result. import Ability from '@ohos.application.Ability' ``` +## How to Use + +The permission request result is obtained through an **AbilityStage** instance. + +```js +import Ability from '@ohos.application.Ability' +export default class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + var permissions=['com.example.permission'] + var permissionRequestResult; + this.context.requestPermissionsFromUser(permissions,(err,result) => { + if(err){ + console.log('requestPermissionsFromUserError: ' + JSON.stringify(err)); + }else{ + permissionRequestResult=result; + console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); + } + }); + } +} +``` + + ## Attributes **System capability**: SystemCapability.Ability.AbilityRuntime.Core diff --git a/en/application-dev/reference/apis/js-apis-plainarray.md b/en/application-dev/reference/apis/js-apis-plainarray.md index 3f0475a9dccbf4efb61836c7fa735174bb060d1e..237dfe4234e2eb9049e419bfe94d051c2aab893e 100644 --- a/en/application-dev/reference/apis/js-apis-plainarray.md +++ b/en/application-dev/reference/apis/js-apis-plainarray.md @@ -1,27 +1,34 @@ # Nonlinear Container PlainArray -> ![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. +**PlainArray** stores key-value (KV) pairs. Each key must be unique, be of the number type, and have only one value. + +**PlainArray** is based on generics and uses a lightweight structure. Keys in the array are searched using binary search, which map to values in other arrays. + +Both **PlainArray** and **[LightWeightMap](js-apis-lightweightmap.md)** are used to store KV pairs in the lightweight structure. However, the key type of **PlainArray** can only be **number**. + +**Recommended use case**: Use **PlainArray** when you need to store KV pairs whose keys are of the **number** type. ## Modules to Import ```ts -import PlainArray from '@ohos.util.PlainArray' +import PlainArray from '@ohos.util.PlainArray'; ``` -## System Capability -SystemCapability.Utils.Lang ## PlainArray - ### Attributes +**System capability**: SystemCapability.Utils.Lang + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Number of entries in a plain array (called container later).| +| length | number | Yes| No| Number of elements in a plain array (called container later).| ### constructor @@ -30,6 +37,8 @@ constructor() A constructor used to create a **PlainArray** instance. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -43,6 +52,8 @@ isEmpty(): boolean Checks whether this container is empty. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -63,11 +74,13 @@ has(key: number): boolean Checks whether this container contains the specified key. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | number | Yes| Key to check.| +| key | number | Yes| Target key.| **Return value** @@ -91,11 +104,13 @@ get(key: number): T Obtains the value of the specified key in this container. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | number | Yes| Key to query.| +| key | number | Yes| Target key.| **Return value** @@ -117,19 +132,21 @@ let result = plainArray.get(1); getIndexOfKey(key: number): number -Obtains the index of the first occurrence of an entry with the specified key in this container. +Obtains the index of the first occurrence of an element with the specified key in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | number | Yes| Key of the entry to obtain.| +| key | number | Yes| Target key.| **Return value** | Type| Description| | -------- | -------- | -| number | Returns the position index if obtained; returns **-1** if the specified entry is not found.| +| number | Returns the position index if obtained; returns **-1** otherwise.| **Example** @@ -137,7 +154,7 @@ Obtains the index of the first occurrence of an entry with the specified key in let plainArray = new PlainArray(); plainArray.add(1, "sddfhf"); plainArray.add(2, "sffdfhf"); -let result = plainArray.getIndexOfKey("sdfs"); +let result = plainArray.getIndexOfKey(2); ``` @@ -145,19 +162,21 @@ let result = plainArray.getIndexOfKey("sdfs"); getIndexOfValue(value: T): number -Obtains the index of the first occurrence of an entry with the specified value in this container. +Obtains the index of the first occurrence of an element with the specified value in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Value of the entry to obtain.| +| value | T | Yes| Value of the target element.| **Return value** | Type| Description| | -------- | -------- | -| number | Returns the position index if obtained; returns **-1** if the specified entry is not found.| +| number | Returns the position index if obtained; returns **-1** otherwise.| **Example** @@ -173,19 +192,21 @@ let result = plainArray.getIndexOfValue("sddfhf"); getKeyAt(index: number): number -Obtains the key of the entry at the specified position in this container. +Obtains the key of the element at the specified position in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry to obtain.| +| index | number | Yes| Position index of the target element.| **Return value** | Type| Description| | -------- | -------- | -| number | Returns the key of the entry if obtained; returns **-1** otherwise.| +| number | Returns the key of the element if obtained; returns **-1** otherwise.| **Example** @@ -200,19 +221,21 @@ let result = plainArray.getKeyAt(1); getValueAt(index: number): T -Obtains the value of an entry at the specified position in this container. +Obtains the value of an element at the specified position in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name| Type | Mandatory| Description| - | -------- | -------- | -------- | -------- | - | index | number | Yes| Position index of the entry to obtain.| +| Name| Type | Mandatory| Description| +| -------- | -------- | -------- | -------- | +| index | number | Yes| Position index of the target element.| **Return value** - | Type| Description| - | -------- | -------- | - | T | Returns the value of the entry if obtained; returns **undefined** otherwise.| +| Type| Description| +| -------- | -------- | +| T | Returns the value of the element if obtained; returns **undefined** otherwise.| **Example** @@ -229,6 +252,8 @@ clone(): PlainArray<T> Clones this container and returns a copy. The modification to the copy does not affect the original instance. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -249,14 +274,16 @@ let newPlainArray = plainArray.clone(); add(key: number, value: T): void -Adds an entry to this container. +Adds an element to this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | number | Yes| Key of the entry to add.| -| value | T | Yes| Value of the entry to add.| +| key | number | Yes| Key of the target element.| +| value | T | Yes| Value of the target element.| **Example** @@ -270,19 +297,21 @@ plainArray.add(1, "sddfhf"); remove(key: number): T -Removes an entry with the specified key from this container. +Removes an element with the specified key from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | number | Yes| Key of the entry to remove.| +| key | number | Yes| Target key.| **Return value** | Type| Description| | -------- | -------- | -| T | Value of the entry removed.| +| T | Value of the element removed.| **Example** @@ -299,19 +328,21 @@ let result = plainArray.remove(2); removeAt(index: number): T -Removes an entry at the specified position from this container. +Removes an element at the specified position from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry to remove.| +| index | number | Yes| Position index of the target element.| **Return value** | Type| Description| | -------- | -------- | -| T | Entry removed.| +| T | Element removed.| **Example** @@ -328,20 +359,22 @@ let result = plainArray.removeAt(1); removeRangeFrom(index: number, size: number): number -Removes entries in a specified range from this container. +Removes elements in a specified range from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Start position of the entries to remove.| -| size | number | Yes| Number of entries to remove.| +| index | number | Yes| Start position of the elements to remove.| +| size | number | Yes| Number of elements to remove.| **Return value** | Type| Description| | -------- | -------- | -| number | Number of entries removed.| +| number | Number of elements removed.| **Example** @@ -357,14 +390,16 @@ let result = plainArray.removeRangeFrom(1, 3); setValueAt(index: number, value: T): void -Sets a value for an entry at the specified position in this container. +Sets a value for an element at the specified position in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry.| -| value | T | Yes| Value of the entry to set.| +| index | number | Yes| Position index of the target element.| +| value | T | Yes| Value of the target element.| **Example** @@ -380,7 +415,9 @@ plainArray.setValueAt(1, 3546); toString(): String -Obtains a string that contains all entries in this container. +Obtains a string that contains all elements in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -404,6 +441,8 @@ clear(): void Clears this container and sets its length to **0**. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -418,20 +457,22 @@ plainArray.clear(); forEach(callbackfn: (value: T, index?: number, PlainArray?: PlainArray<T>) => void, thisArg?: Object): void -Uses a callback to traverse the entries in this container and obtain their position indexes. +Uses a callback to traverse the elements in this container and obtain their position indexes. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.| +| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Value of the entry that is currently traversed.| -| index | number | No| Key of the entry that is currently traversed.| +| value | T | Yes| Value of the element that is currently traversed.| +| index | number | No| Key of the element that is currently traversed.| | PlainArray | PlainArray<T>| No| Instance that invokes the **forEach** API.| **Example** @@ -440,8 +481,8 @@ callbackfn let plainArray = new PlainArray(); plainArray.add(1, "sddfhf"); plainArray.add(2, "sffdfhf"); -plainArray.forEach((value, key) => { - console.log(value, key); +plainArray.forEach((value, index) => { + console.log("value:" + value, index); }); ``` @@ -452,6 +493,8 @@ plainArray.forEach((value, key) => { Obtains an iterator, each item of which is a JavaScript object. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -467,16 +510,16 @@ plainArray.add(2, "sffdfhf"); // Method 1: for (let item of plainArray) { - console.log("index: " + item[0]); - console.log("value: " + item[1]); + console.log("index:" + item[0]); + console.log("value:" + item[1]); } // Method 2: let iter = plainArray[Symbol.iterator](); let temp = iter.next().value; while(temp != undefined) { - console.log(temp[0]); - console.log(temp[1]); + console.log("index:" + temp[0]); + console.log("value:" + temp[1]); temp = iter.next().value; } ``` diff --git a/en/application-dev/reference/apis/js-apis-process.md b/en/application-dev/reference/apis/js-apis-process.md index e8f5549c0edbefd8d5a5b3645a57e7955753bf20..e73c4fe303ebeaac19274d5214085fb8646fa651 100755 --- a/en/application-dev/reference/apis/js-apis-process.md +++ b/en/application-dev/reference/apis/js-apis-process.md @@ -232,7 +232,7 @@ Checks whether this process is running in a 64-bit environment. **Example** ```js -var ressult = process.is64Bit(); +var result = process.is64Bit(); ``` diff --git a/en/application-dev/reference/apis/js-apis-processrunninginfo.md b/en/application-dev/reference/apis/js-apis-processrunninginfo.md index 63f61d7472be78055c0c4612aa154b2f9eb4c922..24fb9f15a5427a450ea907bb296c43f3d3f55a91 100644 --- a/en/application-dev/reference/apis/js-apis-processrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-processrunninginfo.md @@ -1,9 +1,9 @@ # ProcessRunningInfo -> **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. - Provides process running information. ## Modules to Import @@ -14,11 +14,8 @@ import appManager from '@ohos.application.appManager' ## Usage - The process running information is obtained through an **appManager** instance. - - ```js import appManager from '@ohos.application.appManager'; appManager.getProcessRunningInfos((error,data) => { diff --git a/en/application-dev/reference/apis/js-apis-prompt.md b/en/application-dev/reference/apis/js-apis-prompt.md index 3b4523f4f2e3d85ba3f53cf41ce4aa719d777526..3facc0146ebe2484672cffb3c9a45d0ac7d9f164 100644 --- a/en/application-dev/reference/apis/js-apis-prompt.md +++ b/en/application-dev/reference/apis/js-apis-prompt.md @@ -1,6 +1,6 @@ # Prompt -> ![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. ## Modules to Import @@ -208,7 +208,7 @@ Shows an action menu. This API uses a callback to return the result asynchronous ## prompt.showActionMenu -showActionMenu(options: ActionMenuOptions): Promise +showActionMenu(options: ActionMenuOptions): Promise\ Shows an action menu. This API uses a promise to return the result synchronously. diff --git a/en/application-dev/reference/apis/js-apis-queue.md b/en/application-dev/reference/apis/js-apis-queue.md index ff80fc9e5e8dc3acfe5dbe12c3041a44f5d8e57b..a31a72649d0e0ede56771f3fa6c9bf4d25bbefe7 100644 --- a/en/application-dev/reference/apis/js-apis-queue.md +++ b/en/application-dev/reference/apis/js-apis-queue.md @@ -1,28 +1,31 @@ # Linear Container Queue -> ![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. +**Queue** follows the principle of First In First Out (FIFO). It supports insertion of elements at the end and removal from the front of the queue. **Queue** is implemented based on the queue data structure. + +Unlike **[Deque](js-apis-deque.md)**, which supports insertion and removal at both the ends, **Queue** supports insertion at one end and removal at the other end. + +**Recommended use case**: Use **Queue** in FIFO scenarios. ## Modules to Import ```ts -import Queue from '@ohos.util.Queue' +import Queue from '@ohos.util.Queue'; ``` -## System Capabilities - -SystemCapability.Utils.Lang - ## Queue - ### Attributes +**System capability**: SystemCapability.Utils.Lang + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Number of entries in a queue (called container later).| +| length | number | Yes| No| Number of elements in a queue (called container later).| ### constructor @@ -31,6 +34,8 @@ constructor() A constructor used to create a **Queue** instance. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -42,19 +47,21 @@ let queue = new Queue(); add(element: T): boolean -Adds an entry at the end of this container. +Adds an element at the end of this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to add.| +| element | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the entry is added successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is added successfully; returns **false** otherwise.| **Example** @@ -73,13 +80,15 @@ let result3 = queue.add(c); pop(): T -Removes the first entry from this container. +Removes the first element from this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Type| Description| | -------- | -------- | -| T | Entry removed.| +| T | Element removed.| **Example** @@ -97,13 +106,15 @@ let result = queue.pop(); getFirst(): T -Obtains the first entry of this container. +Obtains the first element of this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Type| Description| | -------- | -------- | -| T | The first entry obtained.| +| T | The first element obtained.| **Example** @@ -121,21 +132,23 @@ let result = queue.getFirst(); forEach(callbackfn: (value: T, index?: number, Queue?: Queue<T>) => void, thisArg?: Object): void -Uses a callback to traverse the entries in this container and obtain their position indexes. +Uses a callback to traverse the elements in this container and obtain their position indexes. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.| +| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Value of the entry that is currently traversed.| -| index | number | No| Position index of the entry that is currently traversed.| +| value | T | Yes| Value of the element that is currently traversed.| +| index | number | No| Position index of the element that is currently traversed.| | Queue | Queue<T> | No| Instance that invokes the **forEach** method.| **Example** @@ -147,7 +160,7 @@ queue.add(4); queue.add(5); queue.add(4); queue.forEach((value, index) => { - console.log(value, index); + console.log("value:" + value, index); }); ``` @@ -156,14 +169,15 @@ queue.forEach((value, index) => { [Symbol.iterator]\(): IterableIterator<T> - Obtains an iterator, each item of which is a JavaScript object. +**System capability**: SystemCapability.Utils.Lang + **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| IterableIterator<T> | Iterator obtained. | +| IterableIterator<T> | Iterator obtained.| **Example** ```ts @@ -175,14 +189,14 @@ queue.add(4); // Method 1: for (let item of queue) { - console.log(item); + console.log("value:" + item); } // Method 2: let iter = queue[Symbol.iterator](); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value:" + temp); temp = iter.next().value; } ``` diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 4df1f4e33d37e28fc1ea83d7fde57d32c21df143..86d29eebedf8fb206589a7770a92362a79873c69 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -408,7 +408,7 @@ Checks whether the current device supports 5G \(NR\). ```js let slotId = 0; let result = radio.isNrSupported(slotId); -console.log(result); +console.log("Result: "+ result); ``` diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index 0a4b8c5ac6d2570ba34b5567322fef99e6b8bb1f..98ff862ea6932d76bed8ba8a8de4a9b452e54a11 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -1,37 +1,36 @@ # Upload and Download -> ![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. -> +> **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. ## Modules to Import -``` +```js import request from '@ohos.request'; ``` ## Constraints -- HTTPS is supported by default. To support HTTP, you need to add **network** to the **config.json** file and set the **cleartextTraffic** attribute to **true**. - - ``` - "deviceConfig": { - "default": { - "network": { - "cleartextTraffic": true - } - ... +HTTPS is supported by default. To support HTTP, you need to add **network** to the **config.json** file and set the **cleartextTraffic** attribute to **true**. + +``` + "deviceConfig": { + "default": { + "network": { + "cleartextTraffic": true } + ... } - ``` + } +``` ## Constants -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -65,7 +64,7 @@ upload(config: UploadConfig): Promise<UploadTask> Uploads files. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -84,11 +83,15 @@ Uploads files. This API uses a promise to return the result. **Example** ```js -request.upload({ url: 'https://patch' }).then((data) => { - uploadTask = data; -}).catch((err) => { - console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); -}) + let file1 = { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }; + let data = { name: "name123", value: "123" }; + let header = { key1: "value1", key2: "value2" }; + let uploadTask; + request.upload({ url: 'https://patch', header: header, method: "POST", files: [file1], data: [data] }).then((data) => { + uploadTask = data; + }).catch((err) => { + console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); + }) ``` @@ -98,7 +101,7 @@ upload(config: UploadConfig, callback: AsyncCallback<UploadTask>): void Uploads files. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -112,19 +115,23 @@ Uploads files. This API uses an asynchronous callback to return the result. **Example** ```js -request.upload({ url: 'https://patch' }, (err, data) => { - if (err) { - console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); - return; - } - uploadTask = data; -}); + let file1 = { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }; + let data = { name: "name123", value: "123" }; + let header = { key1: "value1", key2: "value2" }; + let uploadTask; + request.upload({ url: 'https://patch', header: header, method: "POST", files: [file1], data: [data] }, (err, data) => { + if (err) { + console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); + return; + } + uploadTask = data; + }); ``` ## UploadTask -Implements file uploads. Before using a method of this class, you must obtain an **UploadTask** object. +Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object. ### on('progress') @@ -133,7 +140,7 @@ on(type: 'progress', callback:(uploadedSize: number, totalSize: number) => vo Subscribes to the upload progress event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -154,10 +161,10 @@ Parameters of the callback function **Example** ```js -uploadTask.on('progress', function callback(uploadedSize, totalSize) { - console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize); -} -); + uploadTask.on('progress', function callback(uploadedSize, totalSize) { + console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize); + } + ); ``` @@ -167,7 +174,7 @@ on(type: 'headerReceive', callback: (header: object) => void): void Subscribes to the **headerReceive** event, which is triggered when an HTTP response header is received. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -187,10 +194,10 @@ Parameters of the callback function **Example** ```js -uploadTask.on('headerReceive', function callback(headers){ - console.info("upOnHeader headers:" + JSON.stringify(headers)); -} -); + uploadTask.on('headerReceive', function callback(headers){ + console.info("upOnHeader headers:" + JSON.stringify(headers)); + } + ); ``` @@ -200,7 +207,7 @@ off(type: 'progress', callback?: (uploadedSize: number, totalSize: number) =&g Unsubscribes from the upload progress event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -221,10 +228,10 @@ Parameters of the callback function **Example** ```js -uploadTask.off('progress', function callback(uploadedSize, totalSize) { - console.info('uploadedSize: ' + uploadedSize, 'totalSize: ' + totalSize); -} -); + uploadTask.off('progress', function callback(uploadedSize, totalSize) { + console.info('uploadedSize: ' + uploadedSize, 'totalSize: ' + totalSize); + } + ); ``` @@ -234,7 +241,7 @@ off(type: 'headerReceive', callback?: (header: object) => void): void Unsubscribes from the **headerReceive** event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -254,10 +261,10 @@ Parameters of the callback function **Example** ```js -uploadTask.off('headerReceive', function callback(headers) { - console.info("upOnHeader headers:" + JSON.stringify(headers)); -} -); + uploadTask.off('headerReceive', function callback(headers) { + console.info("upOnHeader headers:" + JSON.stringify(headers)); + } + ); ``` @@ -267,7 +274,7 @@ remove(): Promise<boolean> Removes this upload task. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -280,15 +287,15 @@ Removes this upload task. This API uses a promise to return the result. **Example** ```js -uploadTask.remove().then((result) => { - if (result) { - console.info('Upload task removed successfully. '); - } else { - console.error('Failed to remove the upload task. '); - } -}).catch((err) => { - console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); -}); + uploadTask.remove().then((result) => { + if (result) { + console.info('Upload task removed successfully. '); + } else { + console.error('Failed to remove the upload task. '); + } + }).catch((err) => { + console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); + }); ``` @@ -298,7 +305,7 @@ remove(callback: AsyncCallback<boolean>): void Removes this upload task. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -311,17 +318,17 @@ Removes this upload task. This API uses an asynchronous callback to return the r **Example** ```js -uploadTask.remove((err, result) => { - if (err) { - console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); - return; - } - if (result) { - console.info('Upload task removed successfully.'); - } else { - console.error('Failed to remove the upload task.'); - } -}); + uploadTask.remove((err, result) => { + if (err) { + console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Upload task removed successfully.'); + } else { + console.error('Failed to remove the upload task.'); + } + }); ``` @@ -332,10 +339,10 @@ uploadTask.remove((err, result) => { | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | url | string | Yes | Resource URL. | -| header | object | No | HTTP or HTTPS header added to an upload request. | -| method | string | No | Request methods available: **POST** and **PUT**. The default value is **POST**. | +| header | object | Yes | HTTP or HTTPS header added to an upload request. | +| method | string | Yes | Request methods available: **POST** and **PUT**. The default value is **POST**. | | files | Array<[File](#file)> | Yes | List of files to upload, which is submitted through **multipart/form-data**. | -| data | Array<[RequestData](#requestdata)> | No | Form data in the request body. | +| data | Array<[RequestData](#requestdata)> | Yes | Form data in the request body. | ## File @@ -346,7 +353,7 @@ uploadTask.remove((err, result) => { | -------- | -------- | -------- | -------- | | filename | string | No | File name in the header when **multipart** is used. | | name | string | No | Name of a form item when **multipart** is used. The default value is **file**. | -| uri | string | Yes | Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. The following is an example:
dataability:///com.domainname.dataability.persondata/person/10/file.txt
internal://cache/path/to/file.txt | +| uri | string | Yes | Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. Below are examples:
dataability:///com.domainname.dataability.persondata/person/10/file.txt
internal://cache/path/to/file.txt | | type | string | No | Type of the file content. By default, the type is obtained based on the extension of the file name or URI. | @@ -366,7 +373,7 @@ download(config: DownloadConfig): Promise<DownloadTask> Downloads files. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -384,13 +391,14 @@ Downloads files. This API uses a promise to return the result. **Example** -```js -request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => { - downloadTask = data; -}).catch((err) => { - console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); -}) -``` + ```js + let downloadTask; + request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => { + downloadTask = data; + }).catch((err) => { + console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); + }) + ``` ## request.download @@ -399,7 +407,7 @@ download(config: DownloadConfig, callback: AsyncCallback<DownloadTask>): v Downloads files. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -413,14 +421,15 @@ Downloads files. This API uses an asynchronous callback to return the result. **Example** ```js -request.download({ url: 'https://xxxx/xxxxx.hap', -filePath: 'xxx/xxxxx.hap'}, (err, data) => { - if (err) { - console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); - return; - } - downloadTask = data; -}); + let downloadTask; + request.download({ url: 'https://xxxx/xxxxx.hap', + filePath: 'xxx/xxxxx.hap'}, (err, data) => { + if (err) { + console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); + return; + } + downloadTask = data; + }); ``` @@ -435,7 +444,7 @@ on(type: 'progress', callback:(receivedSize: number, totalSize: number) => vo Subscribes to the download progress event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -456,12 +465,6 @@ Parameters of the callback function **Example** ```js - request.download({ url: 'https://xxxx/xxxx.hap' }, (err, data)=> { - if (err) { - console.error('Failed to request download. Cause:' + err); - return; - } - downloadTask = data; downloadTask.on('progress', function download_callback(receivedSize, totalSize) { console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); } @@ -476,7 +479,7 @@ off(type: 'progress', callback?: (receivedSize: number, totalSize: number) => Unsubscribes from the download progress event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -497,17 +500,11 @@ Parameters of the callback function **Example** ```js -request.download({ url: 'https://xxxx/xxxx.hap' }, (err, data)=> { - if (err) { - console.error('Failed to request download. Cause:' + err); - return; - } - downloadTask = data; - downloadTask .off('progress', function download_callback(receivedSize, totalSize) { - console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); - } -); -}); + downloadTask .off('progress', function download_callback(receivedSize, totalSize) { + console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); + } + ); + }); ``` @@ -517,7 +514,7 @@ on(type: 'complete'|'pause'|'remove', callback:() => void): void Subscribes to a download event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -531,17 +528,11 @@ Subscribes to a download event. This API uses an asynchronous callback to return **Example** ```js -request.download({ url: 'https://xxxx/xxxx.hap' }, (err, data)=> { - if (err) { - console.error('Failed to request download. Cause:' + err); - return; - } - downloadTask= data; - downloadTask.on('complete', function callback() { - console.info('Download task completed.'); - } -); -}); + downloadTask.on('complete', function callback() { + console.info('Download task completed.'); + } + ); + }); ``` @@ -551,7 +542,7 @@ off(type: 'complete'|'pause'|'remove', callback?:() => void): void Unsubscribes from the download event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -565,17 +556,11 @@ Unsubscribes from the download event. This API uses an asynchronous callback to **Example** ```js -request.download({ url: 'https://xxxx/xxxx.hap' }, (err, data)=> { - if (err) { - console.error('Failed to request download. Cause:' + JSON.stringify(err)); - return; - } - downloadTask = data; - downloadTask.off('complete', function callback() { - console.info('Download task completed.'); - } -); -}); + downloadTask.off('complete', function callback() { + console.info('Download task completed.'); + } + ); + }); ``` @@ -585,7 +570,7 @@ on(type: 'fail', callback: (err: number) => void): void Subscribes to the download task failure event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -604,18 +589,12 @@ Parameters of the callback function **Example** - ```js -request.download({ url: 'https://xxxx/xxxx.hap' }, (err, data)=> { - if (err) { - console.error('Failed to request download. Cause:' + err); - return; - } - downloadTask = data; - downloadTask.on('fail', function callBack(err) { - console.info('Download task failed. Cause:' + err); - } -); -}); + ```js + downloadTask.on('fail', function callBack(err) { + console.info('Download task failed. Cause:' + err); + } + ); + }); ``` @@ -625,7 +604,7 @@ off(type: 'fail', callback?: (err: number) => void): void Unsubscribes from the download task failure event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -645,12 +624,6 @@ Parameters of the callback function **Example** ```js - request.download({ url: 'https://xxxx/xxxx.hap' }, (err, data)=> { - if (err) { - console.error('Failed to request download. Cause:' + err); - return; - } - downloadTask = data; downloadTask.off('fail', function callBack(err) { console.info('Download task failed. Cause:' + err); } @@ -665,7 +638,7 @@ remove(): Promise<boolean> Removes this download task. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -696,7 +669,7 @@ remove(callback: AsyncCallback<boolean>): void Removes this download task. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -709,17 +682,17 @@ Removes this download task. This API uses an asynchronous callback to return the **Example** ```js -downloadTask.remove((err, result)=>{ - if(err) { - console.error('Failed to remove the download task.'); - return; - } - if (result) { - console.info('Download task removed.'); - } else { - console.error('Failed to remove the download task.'); - } -}); + downloadTask.remove((err, result)=>{ + if(err) { + console.error('Failed to remove the download task.'); + return; + } + if (result) { + console.info('Download task removed.'); + } else { + console.error('Failed to remove the download task.'); + } + }); ``` @@ -729,7 +702,7 @@ query(): Promise<DownloadInfo> Queries this download task. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -742,11 +715,11 @@ Queries this download task. This API uses a promise to return the result. **Example** ```js -downloadTask.query().then((downloadInfo) => { - console.info('Download task queried. Data:' + JSON.stringify(downloadInfo)) -}) .catch((err) => { - console.error('Failed to query the download task. Cause:' + err) -}); + downloadTask.query().then((downloadInfo) => { + console.info('Download task queried. Data:' + JSON.stringify(downloadInfo)) + }) .catch((err) => { + console.error('Failed to query the download task. Cause:' + err) + }); ``` @@ -756,7 +729,7 @@ query(callback: AsyncCallback<DownloadInfo>): void Queries this download task. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -769,13 +742,13 @@ Queries this download task. This API uses an asynchronous callback to return the **Example** ```js -downloadTask.query((err, downloadInfo)=>{ - if(err) { - console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); - } else { - console.info('download query success. data:'+ JSON.stringify(downloadInfo)); - } -}); + downloadTask.query((err, downloadInfo)=>{ + if(err) { + console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); + } else { + console.info('download query success. data:'+ JSON.stringify(downloadInfo)); + } + }); ``` @@ -785,7 +758,7 @@ queryMimeType(): Promise<string> Queries **MimeType** of this download task. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -798,11 +771,11 @@ Queries **MimeType** of this download task. This API uses a promise to return th **Example** ```js -downloadTask.queryMimeType().then((data) => { - console.info('Download task queried. Data:' + JSON.stringify(data)); -}).catch((err) => { - console.error('Failed to query the download MimeType. Cause:' + JSON.stringify(err)) -}); + downloadTask.queryMimeType().then((data) => { + console.info('Download task queried. Data:' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to query the download MimeType. Cause:' + JSON.stringify(err)) + }); ``` @@ -812,7 +785,7 @@ queryMimeType(callback: AsyncCallback<string>): void; Queries **MimeType** of this download task. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -825,13 +798,13 @@ Queries **MimeType** of this download task. This API uses an asynchronous callba **Example** ```js -downloadTask.queryMimeType((err, data)=>{ - if(err) { - console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); - } else { - console.info('Download task queried. data:' + JSON.stringify(data)); - } -}); + downloadTask.queryMimeType((err, data)=>{ + if(err) { + console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); + } else { + console.info('Download task queried. data:' + JSON.stringify(data)); + } + }); ``` @@ -841,7 +814,7 @@ pause(): Promise<void> Pauses this download task. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -854,15 +827,15 @@ Pauses this download task. This API uses a promise to return the result. **Example** ```js -downloadTask.pause().then((result) => { - if (result) { - console.info('Download task paused. '); - } else { - console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); - } -}).catch((err) => { - console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); -}); + downloadTask.pause().then((result) => { + if (result) { + console.info('Download task paused. '); + } else { + console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); + } + }).catch((err) => { + console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); + }); ``` @@ -872,7 +845,7 @@ pause(callback: AsyncCallback<void>): void Pauses this download task. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -885,17 +858,17 @@ Pauses this download task. This API uses an asynchronous callback to return the **Example** ```js -downloadTask.pause((err, result)=>{ - if(err) { - console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); - return; - } - if (result) { - console.info('Download task paused. '); - } else { - console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); - } -}); + downloadTask.pause((err, result)=>{ + if(err) { + console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Download task paused. '); + } else { + console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); + } + }); ``` @@ -905,7 +878,7 @@ resume(): Promise<void> Resumes this download task. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -918,16 +891,16 @@ Resumes this download task. This API uses a promise to return the result. **Example** ```js -downloadTask.resume().then((result) => { - if (result) { - console.info('Download task resumed.') - } else { - console.error('Failed to resume the download task. '); - } - console.info('Download task resumed.') -}).catch((err) => { - console.error('Failed to resume the download task. Cause:' + err); -}); + downloadTask.resume().then((result) => { + if (result) { + console.info('Download task resumed.') + } else { + console.error('Failed to resume the download task. '); + } + console.info('Download task resumed.') + }).catch((err) => { + console.error('Failed to resume the download task. Cause:' + err); + }); ``` @@ -937,7 +910,7 @@ resume(callback: AsyncCallback<void>): void Resumes this download task. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -950,17 +923,17 @@ Resumes this download task. This API uses an asynchronous callback to return the **Example** ```js -downloadTask.resume((err, result)=>{ - if (err) { - console.error('Failed to resume the download task. Cause:' + err); - return; - } - if (result) { - console.info('Download task resumed.'); - } else { - console.error('Failed to resume the download task.'); - } -}); + downloadTask.resume((err, result)=>{ + if (err) { + console.error('Failed to resume the download task. Cause:' + err); + return; + } + if (result) { + console.info('Download task resumed.'); + } else { + console.error('Failed to resume the download task.'); + } + }); ``` 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 2effb8b20a713c2c1f9a27baa8c12cabdcd37cda..335e31cdb21bacd975db26b726f503c0a44e431d 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,7 @@ 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). -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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,31 +12,41 @@ The resource management module provides APIs to obtain information about the cur import resourceManager from '@ohos.resourceManager'; ``` +## Usage + +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. + +``` +this.context.resourceManager; +``` + ## resourceManager.getResourceManager getResourceManager(callback: AsyncCallback<ResourceManager>): void -Obtains the **ResourceManager** object of this application. This API uses a callback to return the result. +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. **System capability**: SystemCapability.Global.ResourceManager **Parameters** | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------- | -| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Asynchronous callback used to return the **ResourceManager** object obtained.| +| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { if (error != null) { - console.log("error occurs" + error); + console.log("error is " + error); return; } mgr.getString(0x1000000, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let str = value; } }); }); @@ -47,7 +57,9 @@ Obtains the **ResourceManager** object of this application. This API uses a call getResourceManager(bundleName: string, callback: AsyncCallback<ResourceManager>): void -Obtains the **ResourceManager** object of an application. This API uses an asynchronous callback to return the result. +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. **System capability**: SystemCapability.Global.ResourceManager @@ -55,7 +67,7 @@ Obtains the **ResourceManager** object of an application. This API uses an async | Name | Type | Mandatory | Description | | ---------- | ---------------------------------------- | ---- | ----------------------------- | | bundleName | string | Yes | Bundle name of the target application. | -| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Asynchronous callback used to return the **ResourceManager** object obtained.| +| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Asynchronous callback used to return the result.| **Example** ``` @@ -70,25 +82,27 @@ 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. + **System capability**: SystemCapability.Global.ResourceManager **Return value** | Type | Description | | ---------------------------------------- | ----------------- | -| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained.| +| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager().then(mgr => { mgr.getString(0x1000000, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let str = value; } }); }).catch(error => { - console.log(error); + console.log("error is " + error); }); ``` @@ -97,7 +111,9 @@ Obtains the **ResourceManager** object of this application. This API uses a prom getResourceManager(bundleName: string): Promise<ResourceManager> -Obtains the **ResourceManager** object of an application. This API uses a promise to return the result. +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. **System capability**: SystemCapability.Global.ResourceManager @@ -109,7 +125,7 @@ Obtains the **ResourceManager** object of an application. This API uses a promis **Return value** | Type | Description | | ---------------------------------------- | ------------------ | -| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained.| +| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the result.| **Example** ``` @@ -129,8 +145,8 @@ Enumerates the screen directions. | Name | Default Value | Description | | -------------------- | ---- | ---- | -| DIRECTION_VERTICAL | 0 | Portrait | -| DIRECTION_HORIZONTAL | 1 | Landscape | +| DIRECTION_VERTICAL | 0 | Portrait. | +| DIRECTION_HORIZONTAL | 1 | Landscape. | ## DeviceType @@ -141,12 +157,12 @@ Enumerates the device types. | Name | Default Value | Description | | -------------------- | ---- | ---- | -| DEVICE_TYPE_PHONE | 0x00 | Phone | -| DEVICE_TYPE_TABLET | 0x01 | Tablet | -| DEVICE_TYPE_CAR | 0x02 | Head unit | -| DEVICE_TYPE_PC | 0x03 | PC | -| DEVICE_TYPE_TV | 0x04 | TV | -| DEVICE_TYPE_WEARABLE | 0x06 | Wearable | +| DEVICE_TYPE_PHONE | 0x00 | Phone. | +| DEVICE_TYPE_TABLET | 0x01 | Tablet. | +| DEVICE_TYPE_CAR | 0x02 | Head unit. | +| DEVICE_TYPE_PC | 0x03 | PC. | +| DEVICE_TYPE_TV | 0x04 | TV. | +| DEVICE_TYPE_WEARABLE | 0x06 | Wearable. | ## ScreenDensity @@ -182,8 +198,8 @@ Defines the device configuration. ``` resourceManager.getResourceManager((error, mgr) => { mgr.getConfiguration((error, value) => { - console.log(value.direction); - console.log(value.locale); + let direction = value.direction; + let locale = value.locale; }); }); ``` @@ -205,8 +221,8 @@ Defines the device capability. ``` resourceManager.getResourceManager((error, mgr) => { mgr.getDeviceCapability((error, value) => { - console.log(value.screenDensity); - console.log(value.deviceType); + let screenDensity = value.screenDensity; + let deviceType = value.deviceType; }); }); ``` @@ -227,7 +243,7 @@ Defines the descriptor information of the raw file.
Defines the capability of accessing application resources. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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**. @@ -245,16 +261,16 @@ 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 obtained string.| +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getString($r('app.string.test').id, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let str = value; } }); }); @@ -277,15 +293,15 @@ Obtains the string corresponding to the specified resource ID. This API uses a p **Return value** | Type | Description | | --------------------- | ----------- | -| Promise<string> | Promise used to return the string obtained.| +| Promise<string> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getString($r('app.string.test').id).then(value => { - console.log(value); + let str = value; }).catch(error => { - console.log("getstring promise " + error); + console.log("getstring promise error is " + error); }); }); ``` @@ -295,7 +311,7 @@ Obtains the string corresponding to the specified resource ID. This API uses a p getStringArray(resId: number, callback: AsyncCallback<Array<string>>): void -Obtains the array of strings corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. +Obtains the string array corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -303,16 +319,16 @@ Obtains the array of strings corresponding to the specified resource ID. This AP | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------- | | resId | number | Yes | Resource ID. | -| callback | AsyncCallback<Array<string>> | Yes | Asynchronous callback used to return the obtained array of strings.| +| callback | AsyncCallback<Array<string>> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getStringArray($r('app.strarray.test').id, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let strArray = value; } }); }); @@ -323,7 +339,7 @@ Obtains the array of strings corresponding to the specified resource ID. This AP getStringArray(resId: number): Promise<Array<string>> -Obtains the array of strings corresponding to the specified resource ID. This API uses a promise to return the result. +Obtains the string array corresponding to the specified resource ID. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -335,15 +351,15 @@ Obtains the array of strings corresponding to the specified resource ID. This AP **Return value** | Type | Description | | ---------------------------------- | ------------- | -| Promise<Array<string>> | Promise used to return the array of strings obtained.| +| Promise<Array<string>> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getStringArray($r('app.strarray.test').id).then(value => { - console.log(value); + let strArray = value; }).catch(error => { - console.log("getstring promise " + error); + console.log("getStringArray promise error is " + error); }); }); ``` @@ -361,16 +377,16 @@ 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 content of the media file obtained.| +| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getMedia($r('app.media.test').id, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let media = value; } }); }); @@ -393,15 +409,15 @@ Obtains the content of the media file corresponding to the specified resource ID **Return value** | Type | Description | | ------------------------- | -------------- | -| Promise<Uint8Array> | Promise used to return the content of the media file obtained.| +| Promise<Uint8Array> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getMedia($r('app.media.test').id).then(value => { - console.log(value); + let media = value; }).catch(error => { - console.log("getstring promise " + error); + console.log("getMedia promise error is " + error); }); }); ``` @@ -419,16 +435,16 @@ 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 Base64 code of the image obtained.| +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getMediaBase64($r('app.media.test').id, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let media = value; } }); }); @@ -451,15 +467,15 @@ Obtains the Base64 code of the image corresponding to the specified resource ID. **Return value** | Type | Description | | --------------------- | -------------------- | -| Promise<string> | Promise used to return the Base64 code of the image obtained.| +| Promise<string> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getMediaBase64($r('app.media.test').id).then(value => { - console.log(value); + let media = value; }).catch(error => { - console.log("getstring promise " + error); + console.log("getMediaBase64 promise error is " + error); }); }); ``` @@ -476,16 +492,17 @@ 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 obtained device configuration.| +| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getConfiguration((error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let direction = value.direction; + let locale = value.locale; } }); }); @@ -503,15 +520,16 @@ Obtains the device configuration. This API uses a promise to return the result. **Return value** | Type | Description | | ---------------------------------------- | ---------------- | -| Promise<[Configuration](#configuration)> | Promise used to return the device configuration.| +| Promise<[Configuration](#configuration)> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getConfiguration().then(value => { - console.log(value); + let direction = value.direction; + let locale = value.locale; }).catch(error => { - console.log("getstring promise " + error); + console.log("getConfiguration promise error is " + error); }); }); ``` @@ -528,16 +546,17 @@ 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 obtained device capability.| +| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getDeviceCapability((error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let screenDensity = value.screenDensity; + let deviceType = value.deviceType; } }); }); @@ -555,15 +574,16 @@ Obtains the device capability. This API uses a promise to return the result. **Return value** | Type | Description | | ---------------------------------------- | ------------------- | -| Promise<[DeviceCapability](#devicecapability)> | Promise used to return the obtained device capability.| +| Promise<[DeviceCapability](#devicecapability)> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getDeviceCapability().then(value => { - console.log(value); + let screenDensity = value.screenDensity; + let deviceType = value.deviceType; }).catch(error => { - console.log("getstring promise " + error); + console.log("getDeviceCapability promise error is " + error); }); }); ``` @@ -582,16 +602,16 @@ Obtains the specified number of singular-plural strings corresponding to the spe | -------- | --------------------------- | ---- | ------------------------------- | | 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 singular-plural string obtained.| +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getPluralString($r("app.plural.test").id, 1, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let str = value; } }); }); @@ -615,15 +635,15 @@ Obtains the specified number of singular-plural strings corresponding to the spe **Return value** | Type | Description | | --------------------- | ------------------------- | -| Promise<string> | Promise used to return the singular-plural string obtained.| +| Promise<string> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getPluralString($r("app.plural.test").id, 1).then(value => { - console.log(value); + let str = value; }).catch(error => { - console.log("getstring promise " + error); + console.log("getPluralString promise error is " + error); }); }); ``` @@ -632,7 +652,7 @@ Obtains the specified number of singular-plural strings corresponding to the spe getRawFile(path: string, callback: AsyncCallback<Uint8Array>): void -Obtains the content of rawfile in the specified path. This API uses an asynchronous callback to return the result. +Obtains the content of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -640,16 +660,16 @@ Obtains the content of rawfile in the specified path. This API uses an asynchron | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ----------------------- | | path | string | Yes | Path of the raw file. | -| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the raw file content, in byte arrays.| +| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getRawFile("test.xml", (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let rawFile = value; } }); }); @@ -659,7 +679,7 @@ Obtains the content of rawfile in the specified path. This API uses an asynchron getRawFile(path: string): Promise<Uint8Array> -Obtains the content of the raw file in the specified path. This API uses a promise to return the result. +Obtains the content of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -671,15 +691,15 @@ Obtains the content of the raw file in the specified path. This API uses a promi **Return value** | Type | Description | | ------------------------- | ----------- | -| Promise<Uint8Array> | Promise used to return the raw file content, in byte arrays.| +| Promise<Uint8Array> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getRawFile("test.xml").then(value => { - console.log(value); + let rawFile = value; }).catch(error => { - console.log("getrawfile promise " + error); + console.log("getRawFile promise error is " + error); }); }); ``` @@ -688,7 +708,7 @@ Obtains the content of the raw file in the specified path. This API uses a promi getRawFileDescriptor(path: string, callback: AsyncCallback<RawFileDescriptor>): void -Obtains the descriptor of the raw file in the specified path. This API uses an asynchronous callback to return the result. +Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -696,14 +716,14 @@ Obtains the descriptor of the raw file in the specified path. This API uses an a | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | -------------------------------- | | path | string | Yes | Path of the raw file. | -| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | Yes | Asynchronous callback used to return the raw file descriptor.| +| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getRawFileDescriptor("test.xml", (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { let fd = value.fd; let offset = value.offset; @@ -717,7 +737,7 @@ Obtains the descriptor of the raw file in the specified path. This API uses an a getRawFileDescriptor(path: string): Promise<RawFileDescriptor> -Obtains the descriptor of the raw file in the specified path. This API uses a promise to return the result. +Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -729,7 +749,7 @@ Obtains the descriptor of the raw file in the specified path. This API uses a pr **Return value** | Type | Description | | ---------------------------------------- | ------------------- | -| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the raw file descriptor.| +| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the result.| **Example** ``` @@ -739,7 +759,7 @@ Obtains the descriptor of the raw file in the specified path. This API uses a pr let offset = value.offset; let length = value.length; }).catch(error => { - console.log("getRawFileDescriptor promise " + error); + console.log("getRawFileDescriptor promise error is " + error); }); }); ``` @@ -748,7 +768,7 @@ Obtains the descriptor of the raw file in the specified path. This API uses a pr closeRawFileDescriptor(path: string, callback: AsyncCallback<void>): void -Closes the descriptor of the raw file in the specified path. This API uses an asynchronous callback to return the result. +Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -763,7 +783,7 @@ Closes the descriptor of the raw file in the specified path. This API uses an as resourceManager.getResourceManager((error, mgr) => { mgr.closeRawFileDescriptor("test.xml", (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } }); }); @@ -773,7 +793,7 @@ Closes the descriptor of the raw file in the specified path. This API uses an as closeRawFileDescriptor(path: string): Promise<void> -Closes the descriptor of the raw file in the specified path. This API uses a promise to return the result. +Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -791,9 +811,9 @@ Closes the descriptor of the raw file in the specified path. This API uses a pro ``` resourceManager.getResourceManager((error, mgr) => { mgr.closeRawFileDescriptor("test.xml").then(value => { - console.log(value); + let result = value; }).catch(error => { - console.log("closeRawFileDescriptor promise " + error); + console.log("closeRawFileDescriptor promise error is " + error); }); }); ``` @@ -809,10 +829,408 @@ Releases the created **resourceManager**. **Example** ``` resourceManager.getResourceManager((error, mgr) => { - mgr.release((error, value) => { - if (error != null) { - console.log(value); - } - }); + mgr.release(); + }); + ``` + +### getStringByName9+ + +getStringByName(resName: string, callback: AsyncCallback<string>): void + +Obtains the string corresponding to the specified resource name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| + +**Example** + ``` + resourceManager.getStringByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let string = value; + } + }); + ``` + +### getStringByName9+ + +getStringByName(resName: string): Promise<string> + +Obtains the string corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| Promise<string> | String corresponding to the resource name.| + +**Example** + ``` + resourceManager.getStringByName("test").then(value => { + let string = value; + }).catch(error => { + console.log("getStringByName promise error is " + error); + }); + ``` + +### getStringArrayByName9+ + +getStringArrayByName(resName: string, callback: AsyncCallback<Array<string>>): void + +Obtains the string array corresponding to the specified resource name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------- | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<Array<string>> | Yes | Asynchronous callback used to return the result.| + +**Example** + ``` + resourceManager.getStringArrayByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let strArray = value; + } + }); + ``` + +### getStringArrayByName9+ + +getStringArrayByName(resName: string): Promise<Array<string>> + +Obtains the string array corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| ---------------------------------- | ------------- | +| Promise<Array<string>> | Promise used to return the result.| + +**Example** + ``` + resourceManager.getStringArrayByName("test").then(value => { + let strArray = value; + }).catch(error => { + console.log("getStringArrayByName promise error is " + error); + }); + ``` + +### getMediaByName9+ + +getMediaByName(resName: string, callback: AsyncCallback<Uint8Array>): void + +Obtains the content of the media file corresponding to the specified resource name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the result.| + +**Example** + ``` + resourceManager.getMediaByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } + }); + ``` + +### getMediaByName9+ + +getMediaByName(resName: string): Promise<Uint8Array> + +Obtains the content of the media file corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| ------------------------- | -------------- | +| Promise<Uint8Array> | Promise used to return the result.| + +**Example** + ``` + resourceManager.getMediaByName("test").then(value => { + let media = value; + }).catch(error => { + console.log("getMediaByName promise error is " + error); + }); + ``` + +### getMediaBase64ByName9+ + +getMediaBase64ByName(resName: string, callback: AsyncCallback<string>): void + +Obtains the Base64 code of the image corresponding to the specified resource name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------ | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| + +**Example** + ``` + resourceManager.getMediaBase64ByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } }); ``` + +### getMediaBase64ByName9+ + +getMediaBase64ByName(resName: string): Promise<string> + +Obtains the Base64 code of the image corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| --------------------- | -------------------- | +| Promise<string> | Promise used to return the result.| + +**Example** + ``` + resourceManager.getMediaByName("test").then(value => { + let media = value; + }).catch(error => { + console.log("getMediaBase64ByName promise error is " + error); + }); + ``` + +### getPluralStringByName9+ + +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. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| 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.| + +**Example** + ``` + resourceManager.getPluralStringByName("test", 1, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } + }); + ``` + +### getPluralStringByName9+ + +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. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| +| num | number | Yes | Number that determines the plural or singular form. | + +**Return value** +| Type | Description | +| --------------------- | ------------------------- | +| Promise<string> | Promise used to return the result.| + +**Example** + ``` + resourceManager.getPluralStringByName("test", 1).then(value => { + let str = value; + }).catch(error => { + console.log("getPluralStringByName promise error is " + error); + }); + ``` + +### getStringSync9+ + +getStringSync(resId: number): string + +Obtains the string corresponding to the specified resource ID. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| string | String corresponding to the specified resource ID.| + +**Example** + ``` + resourceManager.getStringSync($r('app.string.test').id); + ``` + +### getStringByNameSync9+ + +getStringByNameSync(resName: string): string + +Obtains the string corresponding to the specified resource name. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| string | String corresponding to the resource name.| + +**Example** + ``` + resourceManager.getStringByNameSync("test"); + ``` + + ### getBoolean9+ + +getBoolean(resId: number): boolean + +Obtains the Boolean result corresponding to the specified resource ID. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| boolean | Boolean result corresponding to the specified resource ID.| + +**Example** + ``` + resourceManager.getBoolean($r('app.boolean.boolean_test').id); + ``` + +### getBooleanByName9+ + +getBooleanByName(resName: string): boolean + +Obtains the Boolean result corresponding to the specified resource name. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| boolean | Boolean result corresponding to the specified resource name.| + +**Example** + ``` + resourceManager.getBooleanByName("boolean_test"); + ``` + + ### getNumber9+ + +getNumber(resId: number): number + +Obtains the integer or float value corresponding to the specified resource ID. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| number | Integer or float value corresponding to the specified resource ID.| + +**Example** + ``` + resourceManager.getNumber($r('app.integer.integer_test').id); + resourceManager.getNumber($r('app.float.float_test').id); + ``` + +### getNumberByName9+ + +getNumberByName(resName: string): number + +Obtains the integer or float value corresponding to the specified resource name. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| number | Integer or float value corresponding to the specified resource name.| + +**Example** + ``` + resourceManager.getNumberByName("integer_test"); + resourceManager.getNumberByName("float_test"); + ``` diff --git a/en/application-dev/reference/apis/js-apis-rpc.md b/en/application-dev/reference/apis/js-apis-rpc.md index 0f57a0ac5c6754d9e5673086a47beee9fc775ffe..95b60009b09bd8dee7e3a687027d94c070e1b864 100644 --- a/en/application-dev/reference/apis/js-apis-rpc.md +++ b/en/application-dev/reference/apis/js-apis-rpc.md @@ -1,7 +1,7 @@ # RPC -> ![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. @@ -26,12 +26,12 @@ Creates a **MessageParcel** object. This method is a static method. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | MessageParcel | **MessageParcel** object created.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -47,7 +47,7 @@ Reclaims the **MessageParcel** object that is no longer used. **System capability**: SystemCapability.Communication.IPC.Core -- Example +**Example** ``` let reply = rpc.MessageParcel.create(); @@ -63,23 +63,37 @@ writeRemoteObject(object: [IRemoteObject](#iremoteobject)): boolean **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | object | [IRemoteObject](#iremoteobject) | Yes| Remote object to serialize and write to the **MessageParcel** object.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } } let data = rpc.MessageParcel.create(); let testRemoteObject = new TestRemoteObject("testObject"); @@ -95,18 +109,32 @@ Reads the remote object from this **MessageParcel** object. You can use this met **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | [IRemoteObject](#iremoteobject) | Remote object obtained.| -- Example +**Example** ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } } let data = rpc.MessageParcel.create(); let testRemoteObject = new TestRemoteObject("testObject"); @@ -123,17 +151,17 @@ Writes an interface token to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | token | string | Yes| Interface token to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -150,12 +178,12 @@ Reads the interface token from this **MessageParcel** object. The interface toke **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | string | Interface token obtained.| -- Example +**Example** ``` class Stub extends rpc.RemoteObject { @@ -176,12 +204,12 @@ Obtains the data size of this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | Size of the **MessageParcel** object obtained, in bytes.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -198,12 +226,12 @@ Obtains the capacity of this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | **MessageParcel** capacity obtained, in bytes.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -220,17 +248,17 @@ Sets the size of data contained in this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | size | number | Yes| Data size to set, in bytes.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -247,17 +275,17 @@ Sets the storage capacity of this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | size | number | Yes| Storage capacity to set, in bytes.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -274,12 +302,12 @@ Obtains the writable capacity of this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | **MessageParcel** writable capacity obtained, in bytes.| -- Example +**Example** ``` class Stub extends rpc.RemoteObject { @@ -300,12 +328,12 @@ Obtains the readable capacity of this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | **MessageParcel** object readable capacity, in bytes.| -- Example +**Example** ``` class Stub extends rpc.RemoteObject { @@ -326,12 +354,12 @@ Obtains the read position of this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | Current read position of the **MessageParcel** object.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -348,12 +376,12 @@ Obtains the write position of this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | Current write position of the **MessageParcel** object.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -371,17 +399,17 @@ Moves the read pointer to the specified position. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pos | number | Yes| Position from which data is to read.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the read position changes; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -403,17 +431,17 @@ Moves the write pointer to the specified position. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pos | number | Yes| Position from which data is to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the write position changes; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -433,17 +461,17 @@ Writes a Byte value to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | val | number | Yes| Byte value to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -460,12 +488,12 @@ Reads the Byte value from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | Byte value read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -484,17 +512,17 @@ Writes a Short int value to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | val | number | Yes| Short int value to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -511,12 +539,12 @@ Reads the Short int value from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | Short int value read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -535,17 +563,17 @@ Writes an Int value to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | val | number | Yes| Int value to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -562,12 +590,12 @@ Reads the Int value from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | Int value read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -586,17 +614,17 @@ Writes a Long int value to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | val | number | Yes| Long int value to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -613,18 +641,18 @@ Reads the Long int value from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | Long int value read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); let result = data.writeLong(10000); console.log("RpcClient: writeLong is " + result); - let ret = data.readlong(); + let ret = data.readLong(); console.log("RpcClient: readLong is " + ret); ``` @@ -637,17 +665,17 @@ Writes a Float value to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | val | number | Yes| Float value to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -664,12 +692,12 @@ Reads the Float value from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | Float value read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -688,17 +716,17 @@ Writes a Double value to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | val | number | Yes| Double value to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -715,12 +743,12 @@ Reads the Double value from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | Double value read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -739,17 +767,17 @@ Writes a Boolean value to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | val | boolean | Yes| Boolean value to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -766,12 +794,12 @@ Reads the Boolean value from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Boolean value read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -790,21 +818,21 @@ Writes a Char value to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | val | number | Yes| Char value to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); - let result = data.writeChar('a'); + let result = data.writeChar(97); console.log("RpcClient: writeChar is " + result); ``` @@ -817,16 +845,16 @@ Reads the Char value from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | Char value read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); - let result = data.writeChar('a'); + let result = data.writeChar(97); console.log("RpcClient: writeChar is " + result); let ret = data.readChar(); console.log("RpcClient: readChar is " + ret); @@ -841,17 +869,17 @@ Writes a String value to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | val | string | Yes| String value to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -868,12 +896,12 @@ Reads the String value from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | string | String value read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -892,23 +920,25 @@ Writes a sequenceable object to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | val | [Sequenceable](#sequenceable) | Yes| Sequenceable object to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` class MySequenceable { - constructor(num, string) { + num: number; + str: string; + constructor(num, str) { this.num = num; - this.str = string; + this.str = str; } marshalling(messageParcel) { messageParcel.writeInt(this.num); @@ -936,23 +966,25 @@ Reads member variables from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dataIn | [Sequenceable](#sequenceable) | Yes| Object that reads member variables from the **MessageParcel** object.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` class MySequenceable { - constructor(num, string) { + num: number; + str: string; + constructor(num, str) { this.num = num; - this.str = string; + this.str = str; } marshalling(messageParcel) { messageParcel.writeInt(this.num); @@ -983,21 +1015,21 @@ Writes a ByteArray to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | byteArray | number[] | Yes| ByteArray to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); - let ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]); + let ByteArrayVar = [1, 2, 3, 4, 5]; let result = data.writeByteArray(ByteArrayVar); console.log("RpcClient: writeByteArray is " + result); ``` @@ -1011,16 +1043,16 @@ Reads the ByteArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dataIn | number[] | Yes| ByteArray to read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); - let ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]); + let ByteArrayVar = [1, 2, 3, 4, 5]; let result = data.writeByteArray(ByteArrayVar); console.log("RpcClient: writeByteArray is " + result); let array = new Array(5); @@ -1036,16 +1068,16 @@ Reads the ByteArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number[] | ByteArray read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); - let ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]); + let ByteArrayVar = [1, 2, 3, 4, 5]; let result = data.writeByteArray(ByteArrayVar); console.log("RpcClient: writeByteArray is " + result); let array = data.readByteArray(); @@ -1061,17 +1093,17 @@ Writes a ShortArray to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | shortArray | number[] | Yes| ShortArray to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1088,12 +1120,12 @@ Reads a ShortArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dataIn | number[] | Yes| ShortArray to read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1112,12 +1144,12 @@ Reads the ShortArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number[] | ShortArray read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1136,17 +1168,17 @@ Writes an IntArray to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | intArray | number[] | Yes| IntArray to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1163,12 +1195,12 @@ Reads an IntArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dataIn | number[] | Yes| IntArray to read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1187,12 +1219,12 @@ Reads the IntArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number[] | IntArray read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1211,17 +1243,17 @@ Writes a LongArray to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | longArray | number[] | Yes| LongArray to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1238,12 +1270,12 @@ Reads a LongArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dataIn | number[] | Yes| LongArray to read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1262,12 +1294,12 @@ Reads the LongArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number[] | LongArray read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1286,17 +1318,17 @@ Writes a FloatArray to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | floatArray | number[] | Yes| FloatArray to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1313,13 +1345,13 @@ Reads a FloatArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dataIn | number[] | Yes| FloatArray to read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1338,12 +1370,12 @@ Reads the FloatArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number[] | FloatArray read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1362,17 +1394,17 @@ Writes a DoubleArray to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | doubleArray | number[] | Yes| DoubleArray to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1389,12 +1421,12 @@ Reads a DoubleArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dataIn | number[] | Yes| DoubleArray to read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1413,12 +1445,12 @@ Reads the DoubleArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number[] | DoubleArray read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1437,17 +1469,17 @@ Writes a BooleanArray to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | booleanArray | boolean[] | Yes| BooleanArray to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1464,12 +1496,12 @@ Reads a BooleanArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dataIn | boolean[] | Yes| BooleanArray to read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1488,7 +1520,7 @@ Reads the BooleanArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean[] | BooleanArray read.| @@ -1511,21 +1543,21 @@ Writes a CharArray to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | charArray | number[] | Yes| CharArray to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); - let result = data.writeCharArray(['a', 'b', 'c']); + let result = data.writeCharArray([97, 98, 88]); console.log("RpcClient: writeCharArray is " + result); ``` @@ -1538,16 +1570,16 @@ Reads a CharArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dataIn | number[] | Yes| CharArray to read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); - let result = data.writeCharArray(['a', 'b', 'c']); + let result = data.writeCharArray([97, 98, 99]); console.log("RpcClient: writeCharArray is " + result); let array = new Array(3); data.readCharArray(array); @@ -1562,16 +1594,16 @@ Reads the CharArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number[] | CharArray read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); - let result = data.writeCharArray(['a', 'b', 'c']); + let result = data.writeCharArray([97, 98, 99]); console.log("RpcClient: writeCharArray is " + result); let array = data.readCharArray(); console.log("RpcClient: readCharArray is " + array); @@ -1586,17 +1618,17 @@ Writes a StringArray to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | stringArray | string[] | Yes| StringArray to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1613,12 +1645,12 @@ Reads a StringArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dataIn | string[] | Yes| StringArray to read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1637,12 +1669,12 @@ Reads the StringArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | string[] | StringArray read.| -- Example +**Example** ``` let data = rpc.MessageParcel.create(); @@ -1661,13 +1693,27 @@ Writes information to this **MessageParcel** object indicating that no exception **System capability**: SystemCapability.Communication.IPC.Core -- Example +**Example** ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } onRemoteRequest(code, data, reply, option) { if (code === 1) { console.log("RpcServer: onRemoteRequest called"); @@ -1690,7 +1736,7 @@ Reads the exception information from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Example +**Example** ``` import FA from "@ohos.ability.featureAbility"; @@ -1745,23 +1791,25 @@ Writes a SequenceableArray to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sequenceableArray | Sequenceable[] | Yes| SequenceableArray to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` class MySequenceable { - constructor(num, string) { + num: number; + str: string; + constructor(num, str) { this.num = num; - this.str = string; + this.str = str; } marshalling(messageParcel) { messageParcel.writeInt(this.num); @@ -1792,18 +1840,20 @@ Reads a SequenceableArray from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sequenceableArray | Sequenceable[] | Yes| SequenceableArray to read.| -- Example +**Example** ``` class MySequenceable { - constructor(num, string) { + num: number; + str: string; + constructor(num, str) { this.num = num; - this.str = string; + this.str = str; } marshalling(messageParcel) { messageParcel.writeInt(this.num); @@ -1836,24 +1886,41 @@ Writes an array of **IRemoteObject** objects to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | objectArray | IRemoteObject[] | Yes| Array of **IRemoteObject** objects to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** if the operation fails or if the **IRemoteObject** array is null.| -- Example +**Example** ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); this.attachLocalInterface(this, descriptor); } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + asObject(): rpc.IRemoteObject { + return this; + } } let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")]; let data = rpc.MessageParcel.create(); @@ -1870,19 +1937,36 @@ Reads an **IRemoteObject** array from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | objects | IRemoteObject[] | Yes| **IRemoteObject** array to read.| -- Example +**Example** ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); this.attachLocalInterface(this, descriptor); } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + asObject(): rpc.IRemoteObject { + return this; + } } let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")]; let data = rpc.MessageParcel.create(); @@ -1900,19 +1984,36 @@ Reads the **IRemoteObject** array from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | IRemoteObject[] | **IRemoteObject** object array obtained.| -- Example +**Example** ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); this.attachLocalInterface(this, descriptor); } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + asObject(): rpc.IRemoteObject { + return this; + } } let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")]; let data = rpc.MessageParcel.create(); @@ -1931,12 +2032,12 @@ Closes a file descriptor. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | fd | number | Yes| File descriptor to close.| -- Example +**Example** ``` import fileio from '@ohos.fileio'; @@ -1954,17 +2055,17 @@ Duplicates a file descriptor. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | fd | number | Yes| File descriptor to duplicate.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | New file descriptor.| -- Example +**Example** ``` import fileio from '@ohos.fileio'; @@ -1982,12 +2083,12 @@ Checks whether this **MessageParcel** object contains a file descriptor. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the **MessageParcel** object contains a file descriptor; returns **false** otherwise.| -- Example +**Example** ``` import fileio from '@ohos.fileio'; @@ -2010,17 +2111,17 @@ Writes a file descriptor to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | fd | number | Yes| File descriptor to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` import fileio from '@ohos.fileio'; @@ -2040,12 +2141,12 @@ Reads the file descriptor from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | File descriptor read.| -- Example +**Example** ``` import fileio from '@ohos.fileio'; @@ -2066,17 +2167,17 @@ Writes an anonymous shared object to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | ashmem | Ashmem | Yes| Anonymous shared object to write.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let parcel = new rpc.MessageParcel(); @@ -2094,12 +2195,12 @@ Reads the anonymous shared object from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | Ashmem | Anonymous share object obtained.| -- Example +**Example** ``` let parcel = new rpc.MessageParcel(); @@ -2119,12 +2220,12 @@ Obtains the maximum amount of raw data that can be held by this **MessageParcel* **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | 128 MB, which is the maximum amount of raw data that can be held by this **MessageParcel** object.| -- Example +**Example** ``` let parcel = new rpc.MessageParcel(); @@ -2141,22 +2242,22 @@ Writes raw data to this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | rawData | number[] | Yes| Raw data to write.| | size | number | Yes| Size of the raw data, in bytes.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let parcel = new rpc.MessageParcel(); - let arr = new Int8Array([1, 2, 3, 4, 5]); + let arr = [1, 2, 3, 4, 5]; let isWriteSuccess = parcel.writeRawData(arr, arr.length); console.log("RpcTest: parcel write raw data result is : " + isWriteSuccess); ``` @@ -2170,21 +2271,21 @@ Reads raw data from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | size | number | Yes| Size of the raw data to read.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | number[] | Raw data obtained, in bytes.| -- Example +**Example** ``` let parcel = new rpc.MessageParcel(); - let arr = new Int8Array([1, 2, 3, 4, 5]); + let arr = [1, 2, 3, 4, 5]; let isWriteSuccess = parcel.writeRawData(arr, arr.length); console.log("RpcTest: parcel write raw data result is : " + isWriteSuccess); let result = parcel.readRawData(5); @@ -2204,23 +2305,25 @@ Marshals the sequenceable object into a **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dataOut | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object to which the sequenceable object is to be marshaled.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` class MySequenceable { - constructor(num, string) { + num: number; + str: string; + constructor(num, str) { this.num = num; - this.str = string; + this.str = str; } marshalling(messageParcel) { messageParcel.writeInt(this.num); @@ -2251,23 +2354,25 @@ Unmarshals this sequenceable object from a **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dataIn | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object in which the sequenceable object is to be unmarshaled.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` class MySequenceable { - constructor(num, string) { + num: number; + str: string; + constructor(num, str) { this.num = num; - this.str = string; + this.str = str; } marshalling(messageParcel) { messageParcel.writeInt(this.num); @@ -2303,12 +2408,12 @@ Obtains a proxy or remote object. This method must be implemented by its derived **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | [IRemoteObject](#iremoteobject) | Returns the [RemoteObject](#ashmem8) if it is the caller; returns the [IRemoteObject](#iremoteobject), the holder of this **RemoteProxy** object, if the caller is a [RemoteProxy](#remoteproxy) object.| -- Example +**Example** ``` class TestAbility extends rpc.RemoteObject { @@ -2318,10 +2423,11 @@ Obtains a proxy or remote object. This method must be implemented by its derived } ``` -- Example +**Example** ``` class TestProxy { + remote: rpc.RemoteObject; constructor(remote) { this.remote = remote; } @@ -2345,12 +2451,12 @@ Called to perform subsequent operations when a death notification of the remote **System capability**: SystemCapability.Communication.IPC.Core -- Example +**Example** ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } ``` @@ -2383,28 +2489,29 @@ Obtains the interface. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | descriptor | string | Yes| Interface descriptor.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | IRemoteBroker | **IRemoteBroker** object bound to the specified interface descriptor.| -### sendRequest +### sendRequest(deprecated) -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean;7 +> **NOTE**
+> This API is deprecated since API Version 8. You are advised to use [sendRequest8+ ](#sendrequest8). -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult>8+ +sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| @@ -2412,11 +2519,32 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| -- Return value +**Return value** | Type| Description| | -------- | -------- | - | Promise<number>7
Promise<SendRequestResult>8+ | Promise used to return the result. The value **0** will be returned if the request is sent successfully. Otherwise, an error code will be returned.7
Promise used to return the **sendRequestResult** object.8+ | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +### sendRequest8+ + +sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> + +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| + | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| + | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| +**Return value** + | Type| Description| + | -------- | -------- | + | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| ### sendRequest8+ @@ -2426,7 +2554,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| @@ -2444,13 +2572,13 @@ Adds a callback for receiving death notifications of the remote object. This met **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | recipient | [DeathRecipient](#deathrecipient) | Yes| Callback to add.| | flags | number | Yes| Flag of the death notification.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| @@ -2464,13 +2592,13 @@ Removes the callback used to receive death notifications of the remote object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | recipient | [DeathRecipient](#deathrecipient) | Yes| Callback to remove.| | flags | number | Yes| Flag of the death notification.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the callback is removed successfully; returns **false** otherwise.| @@ -2484,7 +2612,7 @@ Obtains the interface descriptor of this object. The interface descriptor is a s **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | string | Interface descriptor obtained.| @@ -2498,7 +2626,7 @@ Checks whether this object is dead. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the object is dead; returns **false** otherwise.| @@ -2521,18 +2649,18 @@ Provides methods to implement **IRemoteObject**. -### sendRequest +### sendRequest(deprecated) -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean;7 +> **NOTE**
+> This API is deprecated since API Version 8. You are advised to use [sendRequest8+ ](#sendrequest8-2). -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult>8+ +sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core - -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| @@ -2540,12 +2668,13 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| -- Return value +**Return value** | Type| Description| | -------- | -------- | - | Promise<number>7
Promise<SendRequestResult>8+ | Promise used to return the result. The value **0** will be returned if the request is sent successfully. Otherwise, an error code will be returned.7
Promise used to return the **sendRequestResult** object.8+ | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + -- Example:7 +**Example** ``` import FA from "@ohos.ability.featureAbility"; @@ -2572,25 +2701,41 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch let reply = rpc.MessageParcel.create(); data.writeInt(1); data.writeString("hello"); - proxy.sendRequest(1, data, reply, option) - .then(function(errCode) { - if (errCode === 0) { - console.log("sendRequest got result"); - let msg = reply.readString(); - console.log("RPCTest: reply msg: " + msg); - } else { - console.log("RPCTest: sendRequest failed, errCode: " + errCode); - } - }).catch(function(e) { - console.log("RPCTest: sendRequest got exception: " + e.message); - }).finally (() => { - console.log("RPCTest: sendRequest ends, reclaim parcel"); - data.reclaim(); - reply.reclaim(); - }); + let ret: boolean = proxy.sendRequest(1, data, reply, option); + if (ret) { + console.log("sendRequest got result"); + let msg = reply.readString(); + console.log("RPCTest: reply msg: " + msg); + } else { + console.log("RPCTest: sendRequest failed"); + } + console.log("RPCTest: sendRequest ends, reclaim parcel"); + data.reclaim(); + reply.reclaim(); ``` -- Example:8+ +### sendRequest8+ + +sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> + +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| + | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| + | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + +**Return value** + | Type| Description| + | -------- | -------- | + | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| + +**Example** ``` import FA from "@ohos.ability.featureAbility"; @@ -2645,7 +2790,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| @@ -2654,7 +2799,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| | callback | AsyncCallback<SendRequestResult> | Yes| Callback for receiving the sending result.| -- Example +**Example** ``` import FA from "@ohos.ability.featureAbility"; @@ -2706,17 +2851,17 @@ Obtains the **LocalInterface** object of an interface descriptor. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | interface | string | Yes| Interface descriptor.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | IRemoteBroker | Returns **Null** by default, which indicates a proxy interface.| -- Example +**Example** ``` import FA from "@ohos.ability.featureAbility"; @@ -2751,18 +2896,18 @@ Adds a callback for receiving the death notifications of the remote object, incl **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | recipient | [DeathRecipient](#deathrecipient) | Yes| Callback to add.| | flags | number | Yes| Flag of the death notification. This parameter is reserved. It is set to **0**.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| -- Example +**Example** ``` import FA from "@ohos.ability.featureAbility"; @@ -2786,7 +2931,7 @@ Adds a callback for receiving the death notifications of the remote object, incl FA.connectAbility(want, connect); class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } let deathRecipient = new MyDeathRecipient(); @@ -2802,18 +2947,18 @@ Removes the callback used to receive death notifications of the remote object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | recipient | [DeathRecipient](#deathrecipient) | Yes| Callback to remove.| | flags | number | Yes| Flag of the death notification. This parameter is reserved. It is set to **0**.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the callback is removed successfully; returns **false** otherwise.| -- Example +**Example** ``` import FA from "@ohos.ability.featureAbility"; @@ -2837,7 +2982,7 @@ Removes the callback used to receive death notifications of the remote object. FA.connectAbility(want, connect); class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } let deathRecipient = new MyDeathRecipient(); @@ -2854,12 +2999,12 @@ Obtains the interface descriptor of this proxy object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | string | Interface descriptor obtained.| -- Example +**Example** ``` import FA from "@ohos.ability.featureAbility"; @@ -2894,12 +3039,12 @@ Checks whether the **RemoteObject** is dead. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the **RemoteObject** is dead; returns **false** otherwise.| -- Example +**Example** ``` import FA from "@ohos.ability.featureAbility"; @@ -2948,7 +3093,7 @@ A constructor used to create a **MessageOption** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | syncFlags | number | No| Call flag, which can be synchronous or asynchronous. The default value is **synchronous**.| @@ -2963,7 +3108,7 @@ Obtains the call flag, which can be synchronous or asynchronous. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | Call mode obtained.| @@ -2977,7 +3122,7 @@ Sets the call flag, which can be synchronous or asynchronous. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | flags | number | Yes| Call flag to set.| @@ -2991,7 +3136,7 @@ Obtains the maximum wait time for this RPC call. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | Maximum wait time obtained.| @@ -3005,7 +3150,7 @@ Sets the maximum wait time for this RPC call. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | waitTime | number | Yes| Maximum wait time to set.| @@ -3024,12 +3169,12 @@ Obtains the system capability manager. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | [IRemoteObject](#iremoteobject) | System capability manager obtained.| -- Example +**Example** ``` let samgr = rpc.IPCSkeleton.getContextObject(); @@ -3045,12 +3190,12 @@ Obtains the PID of the caller. This method is invoked by the **RemoteObject** ob **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | PID of the caller.| -- Example +**Example** ``` class Stub extends rpc.RemoteObject { @@ -3071,12 +3216,12 @@ Obtains the UID of the caller. This method is invoked by the **RemoteObject** ob **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | UID of the caller.| -- Example +**Example** ``` class Stub extends rpc.RemoteObject { @@ -3088,7 +3233,7 @@ Obtains the UID of the caller. This method is invoked by the **RemoteObject** ob } ``` -### getCallingTokenId +### getCallingTokenId8+ static getCallingTokenId(): number; @@ -3096,13 +3241,13 @@ Obtains the caller's token ID, which is used to verify the caller identity. **System capability**: SystemCapability.Communication.IPC.Core -Return value +* Return value | Type | Description | | ------ | --------------------- | | number | Token ID of the caller obtained.| -Example +* Example ``` class Stub extends rpc.RemoteObject { @@ -3115,7 +3260,7 @@ Example ``` -### getCalligDeviceID +### getCallingDeviceID static getCallingDeviceID(): string @@ -3123,17 +3268,17 @@ Obtains the ID of the device hosting the caller's process. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | string | Device ID obtained.| -- Example +**Example** ``` class Stub extends rpc.RemoteObject { onRemoteRequest(code, data, reply, option) { - let callerDeviceID = rpc.IPCSkeleton.getCalligDeviceID(); + let callerDeviceID = rpc.IPCSkeleton.getCallingDeviceID(); console.log("RpcServer: callerDeviceID is: " + callerDeviceID); return true; } @@ -3149,12 +3294,12 @@ Obtains the local device ID. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | string | Local device ID obtained.| -- Example +**Example** ``` class Stub extends rpc.RemoteObject { @@ -3175,12 +3320,12 @@ Checks whether the remote process is a process of the local device. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the local and remote processes are on the same device; returns **false** otherwise.| -- Example +**Example** ``` class Stub extends rpc.RemoteObject { @@ -3201,21 +3346,40 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | object | [IRemoteObject](#iremoteobject) | Yes| **RemoteProxy** specified. | -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | Returns **0** if the operation is successful; returns an error code if the input object is null or a **RemoteObject**, or if the operation fails.| -- Example +**Example** ``` - let remoteObject = new rpc.RemoteObject("aaa", 3); + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + } + let remoteObject = new TestRemoteObject("aaa"); let ret = rpc.IPCSkeleton.flushCommands(remoteObject); console.log("RpcServer: flushCommands result: " + ret); ``` @@ -3229,12 +3393,12 @@ Changes the UID and PID of the remote user to the UID and PID of the local user. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | string | String containing the UID and PID of the remote user.| -- Example +**Example** ``` class Stub extends rpc.RemoteObject { @@ -3255,17 +3419,17 @@ Restores the UID and PID of the remote user. It is usually called when the UID a **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | identity | string | Yes| String containing the remote user UID and PID, which are returned by **resetCallingIdentity**.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` class Stub extends rpc.RemoteObject { @@ -3297,23 +3461,24 @@ A constructor used to create a **RemoteObject** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | descriptor | string | Yes| Interface descriptor.| -### sendRequest +### sendRequest(deprecated) -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean;7 +> **NOTE**
+> This API is deprecated since API Version 8. You are advised to use [sendRequest8+ ](#sendrequest8-4). -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult>8+ +sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| @@ -3321,19 +3486,33 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| -- Return value +**Return value** | Type| Description| | -------- | -------- | - | Promise<number>7
Promise<SendRequestResult>8+ | Promise used to return the result. The value **0** will be returned if the request is sent successfully. Otherwise, an error code will be returned.7
Promise used to return the **sendRequestResult** object.8+ | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example7 +**Example** ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } } let testRemoteObject = new TestRemoteObject("testObject"); let option = new rpc.MessageOption(); @@ -3341,32 +3520,63 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch let reply = rpc.MessageParcel.create(); data.writeInt(1); data.writeString("hello"); - testRemoteObject.sendRequest(1, data, reply, option) - .then(function(errCode) { - if (errCode === 0) { - console.log("sendRequest got result"); - let msg = reply.readString(); - console.log("RPCTest: reply msg: " + msg); - } else { - console.log("RPCTest: sendRequest failed, errCode: " + errCode); - } - }).catch(function(e) { - console.log("RPCTest: sendRequest got exception: " + e.message); - }).finally (() => { - console.log("RPCTest: sendRequest ends, reclaim parcel"); - data.reclaim(); - reply.reclaim(); - }); + let ret: boolean = testRemoteObject.sendRequest(1, data, reply, option); + if (ret) { + console.log("sendRequest got result"); + let msg = reply.readString(); + console.log("RPCTest: reply msg: " + msg); + } else { + console.log("RPCTest: sendRequest failed"); + } + console.log("RPCTest: sendRequest ends, reclaim parcel"); + data.reclaim(); + reply.reclaim(); ``` -- Example8+ +### sendRequest8+ + +sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> + +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| + | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| + | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + +**Return value** + | Type| Description| + | -------- | -------- | + | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| + + +**Example** ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } } let testRemoteObject = new TestRemoteObject("testObject"); let option = new rpc.MessageOption(); @@ -3402,7 +3612,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| @@ -3412,13 +3622,27 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch | AsyncCallback | AsyncCallback<SendRequestResult> | Yes| Callback for receiving the sending result.| -- Example +**Example** ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } } function sendRequestCallback(result) { if (result.errCode === 0) { @@ -3451,7 +3675,7 @@ Provides a response to **sendRequest()**. The server processes the request and r **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | code | number | Yes| Service request code sent by the remote end.| @@ -3459,19 +3683,33 @@ Provides a response to **sendRequest()**. The server processes the request and r | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object carrying the result.| | option | [MessageOption](#messageoption) | Yes| Whether the operation is synchronous or asynchronous.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } onRemoteRequest(code, data, reply, option) { if (code === 1) { @@ -3494,19 +3732,33 @@ Obtains the UID of the remote process. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | UID of the remote process obtained.| -- Example +**Example** ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } } let testRemoteObject = new TestRemoteObject("testObject"); console.log("RpcServer: getCallingUid: " + testRemoteObject.getCallingUid()); @@ -3521,19 +3773,33 @@ Obtains the PID of the remote process. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | PID of the remote process obtained.| -- Example +**Example** ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } } let testRemoteObject = new TestRemoteObject("testObject"); console.log("RpcServer: getCallingPid: " + testRemoteObject.getCallingPid()); @@ -3548,24 +3814,38 @@ Checks whether the remote object corresponding to the specified interface descri **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | descriptor | string | Yes| Interface descriptor.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | IRemoteBroker | Returns the remote object if a match is found; returns **Null** otherwise.| -- Example +**Example** ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } } let testRemoteObject = new TestRemoteObject("testObject"); let broker = testRemoteObject.queryLocalInterface("testObject"); @@ -3580,19 +3860,33 @@ Obtains the interface descriptor. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | string | Interface descriptor obtained.| -- Example +**Example** ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } } let testRemoteObject = new TestRemoteObject("testObject"); let descriptor = testRemoteObject.getInterfaceDescriptor(); @@ -3608,21 +3902,38 @@ Binds an interface descriptor to an **IRemoteBroker** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | localInterface | IRemoteBroker | Yes| **IRemoteBroker** object.| | descriptor | string | Yes| Interface descriptor.| -- Example +**Example** ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); this.attachLocalInterface(this, descriptor); } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + asObject(): rpc.IRemoteObject { + return this; + } } let testRemoteObject = new TestRemoteObject("testObject"); ``` @@ -3652,19 +3963,19 @@ Creates an **Ashmem** object with the specified name and size. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | name | string | Yes| Name of the **Ashmem** object to create.| | size | number | Yes| Size (in bytes) of the **Ashmem** object to create.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Ashmem | Returns the **Ashmem** object if it is created successfully; returns null otherwise.| -- Example +**Example** ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); @@ -3681,18 +3992,18 @@ Creates an **Ashmem** object by copying the file descriptor (FD) of an existing **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | ashmem | Ashmem | Yes| Existing **Ashmem** object.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Ashmem | **Ashmem** object created.| -- Example +**Example** ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); @@ -3710,7 +4021,7 @@ Closes this **Ashmem** object. **System capability**: SystemCapability.Communication.IPC.Core -- Example +**Example** ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); @@ -3726,7 +4037,7 @@ Deletes the mappings for the specified address range of this **Ashmem** object. **System capability**: SystemCapability.Communication.IPC.Core -- Example +**Example** ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); @@ -3742,12 +4053,12 @@ Obtains the memory size of this **Ashmem** object. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | **Ashmem** size obtained.| -- Example +**Example** ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); @@ -3764,21 +4075,21 @@ Creates the shared file mapping on the virtual address space of this process. Th **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | mapType | number | Yes| Protection level of the memory region to which the shared file is mapped.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); - let mapReadAndWrite = ashmem.mapAshmem(rpc.Ashmem.PROT_READ | rpc.Ashmem.PROT_WRITE); + let mapReadAndWrite = ashmem.mapAshmem(ashmem.PROT_READ | ashmem.PROT_WRITE); console.log("RpcTest: map ashmem result is : " + mapReadAndWrite); ``` @@ -3791,12 +4102,12 @@ Maps the shared file to the readable and writable virtual address space of the p **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); @@ -3813,12 +4124,12 @@ Maps the shared file to the read-only virtual address space of the process. **System capability**: SystemCapability.Communication.IPC.Core -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); @@ -3835,21 +4146,21 @@ Sets the protection level of the memory region to which the shared file is mappe **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | protectionType | number | Yes| Protection type to set.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); - let result = ashmem.setProtection(rpc.Ashmem.PROT_READ); + let result = ashmem.setProtection(ashmem.PROT_READ); console.log("RpcTest: Ashmem setProtection result is : " + result); ``` @@ -3862,23 +4173,25 @@ Writes data to the shared file associated with this **Ashmem** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | buf | number[] | Yes| Data to write.| | size | number | Yes| Size of the data to write.| | offset | number | Yes| Start position of the data to write in the memory region associated with this **Ashmem** object.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** is the data is written successfully; returns **false** otherwise.| -- Example +**Example** ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); - var ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]); + let mapResult = ashmem.mapReadAndWriteAshmem(); + console.info("RpcTest map ashmem result is " + mapResult); + var ByteArrayVar = [1, 2, 3, 4, 5]; let writeResult = ashmem.writeToAshmem(ByteArrayVar, 5, 0); console.log("RpcTest: write to Ashmem result is : " + writeResult); ``` @@ -3892,23 +4205,25 @@ Reads data from the shared file associated with this **Ashmem** object. **System capability**: SystemCapability.Communication.IPC.Core -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | size | number | Yes| Size of the data to read.| | offset | number | Yes| Start position of the data to read in the memory region associated with this **Ashmem** object.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | number[] | Data read.| -- Example +**Example** ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); - var ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]); + let mapResult = ashmem.mapReadAndWriteAshmem(); + console.info("RpcTest map ashmem result is " + mapResult); + var ByteArrayVar = [1, 2, 3, 4, 5]; let writeResult = ashmem.writeToAshmem(ByteArrayVar, 5, 0); console.log("RpcTest: write to Ashmem result is : " + writeResult); let readResult = ashmem.readFromAshmem(5, 0); diff --git a/en/application-dev/reference/apis/js-apis-screenshot.md b/en/application-dev/reference/apis/js-apis-screenshot.md index 690a77e0d9563a066d7f1da9352aca640b6fbea3..573909893ea8c182e91b739d753a2f36bf244d16 100644 --- a/en/application-dev/reference/apis/js-apis-screenshot.md +++ b/en/application-dev/reference/apis/js-apis-screenshot.md @@ -1,6 +1,7 @@ # Screenshot -> **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. ## Modules to Import @@ -56,14 +57,14 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a cal **System capability**: SystemCapability.WindowManager.WindowManager.Core -**Required permissions**: ohos.permission.CAPTURE_SCREEN +**Required permissions**: ohos.permission.CAPTURE_SCREEN (available only to system applications) **Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | - | options | [ScreenshotOptions](#screenshotoptions) | No | Screenshot options, which consist of **screenRect**, **imageSize**, and **rotation**. You need to set these parameters.| - | callback | AsyncCallback<image.PixelMap> | Yes | Callback used to return a **PixelMap** object. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [ScreenshotOptions](#screenshotoptions) | No | Screenshot options, which consist of **screenRect**, **imageSize**, and **rotation**. You need to set these parameters.| +| callback | AsyncCallback<image.PixelMap> | Yes | Callback used to return a **PixelMap** object. | **Example** @@ -96,7 +97,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a pro **System capability**: SystemCapability.WindowManager.WindowManager.Core -**Required permissions**: ohos.permission.CAPTURE_SCREEN +**Required permissions**: ohos.permission.CAPTURE_SCREEN (available only to system applications) **Parameters** @@ -106,9 +107,9 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a pro **Return value** - | Type | Description | - | ----------------------------- | ----------------------------------------------- | - | Promise<image.PixelMap> | Promise used to return an **image.PixelMap** object.| +| Type | Description | +| ----------------------------- | ----------------------------------------------- | +| Promise<image.PixelMap> | Promise used to return an **image.PixelMap** object.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-securityLabel.md b/en/application-dev/reference/apis/js-apis-securityLabel.md index cda44f9458742770a9470c67c08d3811953a220b..e552e2032a4827e0f7877235d242478a3bff0a81 100644 --- a/en/application-dev/reference/apis/js-apis-securityLabel.md +++ b/en/application-dev/reference/apis/js-apis-securityLabel.md @@ -3,7 +3,7 @@ > **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. -This module provides functions related to file security levels. It provides JS APIs to obtain and set file security levels. +The APIs of this module can be used to obtain and set file security levels. ## Modules to Import @@ -64,7 +64,7 @@ Sets the security label for a file in asynchronous mode. This API uses a promise setSecurityLabel(path:string, dataLevel:string, callback: AsyncCallback<void>):void -Sets the security label for a file in asynchronous mode. This API uses an asynchronous callback to return the result. +Sets the security label for a file in asynchronous mode. This API uses a callback to return the result. **System capability**: SystemCapability.FileManagement.File.DistributedFile @@ -138,7 +138,7 @@ Obtains the security label of a file in asynchronous mode. This API uses a promi getSecurityLabel(path:string, callback:AsyncCallback<string>): void -Obtains the security label of a file in asynchronous mode. This API uses an asynchronous callback to return the result. +Obtains the security label of a file in asynchronous mode. This API uses a callback to return the result. **System capability**: SystemCapability.FileManagement.File.DistributedFile diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index c04e503414020d5c0b6107ef2313df58d91b52f5..aab544f7f78bd2b755ab24443aa1d0acd5d683c1 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -1,17 +1,19 @@ # Sensor -> **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. ## Modules to Import -``` +```js import sensor from '@ohos.sensor'; ``` +## sensor.on -## sensor.on(SensorType.SENSOR_TYPE_ID_ACCELEROMETER) +### ACCELEROMETER on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>,options?: Options): void @@ -30,7 +32,7 @@ Subscribes to data changes of the acceleration sensor. If this API is called mul | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -40,8 +42,7 @@ Subscribes to data changes of the acceleration sensor. If this API is called mul ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) +### LINEAR_ACCELERATION on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>, options?: Options): void @@ -59,7 +60,7 @@ Subscribes to data changes of the linear acceleration sensor. If this API is cal | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -69,8 +70,7 @@ Subscribes to data changes of the linear acceleration sensor. If this API is cal ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) +### ACCELEROMETER_UNCALIBRATED on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>, options?: Options): void @@ -88,7 +88,7 @@ Subscribes to data changes of the uncalibrated acceleration sensor. If this API | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -101,8 +101,7 @@ Subscribes to data changes of the uncalibrated acceleration sensor. If this API ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_GRAVITY) +### GRAVITY on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>,options?: Options): void @@ -118,7 +117,7 @@ Subscribes to data changes of the gravity sensor. If this API is called multiple | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -128,8 +127,7 @@ Subscribes to data changes of the gravity sensor. If this API is called multiple ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_GYROSCOPE) +### GYROSCOPE on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>, options?: Options): void @@ -147,7 +145,7 @@ Subscribes to data changes of the gyroscope sensor. If this API is called multip | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -157,8 +155,7 @@ Subscribes to data changes of the gyroscope sensor. If this API is called multip ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) +### GYROSCOPE_UNCALIBRATED on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:Callback<GyroscopeUncalibratedResponse>, options?: Options): void @@ -176,7 +173,7 @@ Subscribes to data changes of the uncalibrated gyroscope sensor. If this API is | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -189,8 +186,7 @@ Subscribes to data changes of the uncalibrated gyroscope sensor. If this API is ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) +### SIGNIFICANT_MOTION on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>, options?: Options): void @@ -206,7 +202,7 @@ Subscribes to data changes of the significant motion sensor. If this API is call | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(data){ console.info('Scalar data: ' + data.scalar); }, @@ -214,8 +210,7 @@ Subscribes to data changes of the significant motion sensor. If this API is call ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) +### PEDOMETER_DETECTION on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>, options?: Options): void @@ -233,7 +228,7 @@ Subscribes to data changes of the pedometer detection sensor. If this API is cal | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(data){ console.info('Scalar data: ' + data.scalar); }, @@ -241,8 +236,7 @@ Subscribes to data changes of the pedometer detection sensor. If this API is cal ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_PEDOMETER) +### PEDOMETER on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>, options?: Options): void @@ -260,7 +254,7 @@ Subscribes to data changes of the pedometer sensor. If this API is called multip | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(data){ console.info('Steps: ' + data.steps); }, @@ -268,8 +262,7 @@ Subscribes to data changes of the pedometer sensor. If this API is called multip ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +### AMBIENT_TEMPERATURE on(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:Callback<AmbientTemperatureResponse>, options?: Options): void @@ -285,7 +278,7 @@ Subscribes to data changes of the ambient temperature sensor. If this API is cal | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(data){ console.info('Temperature: ' + data.temperature); }, @@ -293,8 +286,7 @@ Subscribes to data changes of the ambient temperature sensor. If this API is cal ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) +### MAGNETIC_FIELD on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>,options?: Options): void @@ -310,7 +302,7 @@ Subscribes to data changes of the magnetic field sensor. If this API is called m | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -320,8 +312,7 @@ Subscribes to data changes of the magnetic field sensor. If this API is called m ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) +### MAGNETIC_FIELD_UNCALIBRATED on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>, options?: Options): void @@ -337,7 +328,7 @@ Subscribes to data changes of the uncalibrated magnetic field sensor. If this AP | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -350,8 +341,7 @@ Subscribes to data changes of the uncalibrated magnetic field sensor. If this AP ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_PROXIMITY) +### PROXIMITY on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>,options?: Options): void @@ -367,7 +357,7 @@ Subscribes to data changes of the proximity sensor. If this API is called multip | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(data){ console.info('Distance: ' + data.distance); }, @@ -375,8 +365,7 @@ Subscribes to data changes of the proximity sensor. If this API is called multip ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_HUMIDITY) +### HUMIDITY on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>,options?: Options): void @@ -392,7 +381,7 @@ Subscribes to data changes of the humidity sensor. If this API is called multipl | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY,function(data){ console.info('Humidity: ' + data.humidity); }, @@ -400,8 +389,7 @@ Subscribes to data changes of the humidity sensor. If this API is called multipl ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_BAROMETER) +### BAROMETER on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>,options?: Options): void @@ -417,7 +405,7 @@ Subscribes to data changes of the barometer sensor. If this API is called multip | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER,function(data){ console.info('Atmospheric pressure: ' + data.pressure); }, @@ -425,8 +413,7 @@ Subscribes to data changes of the barometer sensor. If this API is called multip ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_HALL) +### HALL on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>, options?: Options): void @@ -442,7 +429,7 @@ Subscribes to data changes of the Hall effect sensor. If this API is called mult | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(data){ console.info('Status: ' + data.status); }, @@ -450,8 +437,7 @@ Subscribes to data changes of the Hall effect sensor. If this API is called mult ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) +### AMBIENT_LIGHT on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>, options?: Options): void @@ -467,7 +453,7 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(data){ console.info(' Illumination: ' + data.intensity); }, @@ -475,8 +461,7 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_ORIENTATION) +### ORIENTATION on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>, options?: Options): void @@ -492,7 +477,7 @@ Subscribes to data changes of the orientation sensor. If this API is called mult | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(data){ console.info('The device rotates at an angle around the X axis: ' + data.beta); console.info('The device rotates at an angle around the Y axis: ' + data.gamma); @@ -502,7 +487,7 @@ Subscribes to data changes of the orientation sensor. If this API is called mult ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_HEART_RATE) +### HEART_RATE on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>, options?: Options): void @@ -521,7 +506,7 @@ Subscribes to only one data change of the heart rate sensor. **Example** -``` +```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE,function(data){ console.info("Heart rate: " + data.heartRate); }, @@ -529,7 +514,7 @@ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE,function(data){ ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) +### ROTATION_VECTOR on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback: Callback<RotationVectorResponse>,options?: Options): void @@ -545,7 +530,7 @@ Subscribes to data changes of the rotation vector sensor. If this API is called | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -556,8 +541,7 @@ Subscribes to data changes of the rotation vector sensor. If this API is called ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) +### WEAR_DETECTION on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>,options?: Options): void @@ -573,7 +557,7 @@ Subscribes to data changes of the wear detection sensor. If this API is called m | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(data){ console.info('Wear status: ' + data.value); }, @@ -581,8 +565,9 @@ Subscribes to data changes of the wear detection sensor. If this API is called m ); ``` +## sensor.once -## sensor.once(SensorType.SENSOR_TYPE_ID_ACCELEROMETER) +### ACCELEROMETER once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>): void @@ -599,7 +584,7 @@ Subscribes to only one data change of the acceleration sensor. | callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -608,8 +593,7 @@ Subscribes to only one data change of the acceleration sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) +### LINEAR_ACCELERATION once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>): void @@ -626,7 +610,7 @@ Subscribes to only one data change of the linear acceleration sensor. | callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -635,8 +619,7 @@ Subscribes to only one data change of the linear acceleration sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) +### ACCELEROMETER_UNCALIBRATED once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>): void @@ -665,8 +648,7 @@ Subscribes to only one data change of the uncalibrated acceleration sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_GRAVITY) +### GRAVITY once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>): void @@ -681,7 +663,7 @@ Subscribes to only one data change of the gravity sensor. | callback | Callback<[GravityResponse](#gravityresponse)> | Yes | One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -690,8 +672,7 @@ Subscribes to only one data change of the gravity sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_GYROSCOPE) +### GYROSCOPE once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>): void @@ -708,7 +689,7 @@ Subscribes to only one data change of the gyroscope sensor. | callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -717,8 +698,7 @@ Subscribes to only one data change of the gyroscope sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) +### GYROSCOPE_UNCALIBRATED once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback: Callback<GyroscopeUncalibratedResponse>): void @@ -735,7 +715,7 @@ Subscribes to only one data change of the uncalibrated gyroscope sensor. | callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -747,8 +727,7 @@ Subscribes to only one data change of the uncalibrated gyroscope sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) +### SIGNIFICANT_MOTION once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback: Callback<SignificantMotionResponse>): void @@ -763,15 +742,14 @@ Subscribes to only one data change of the significant motion sensor. | callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(data) { console.info('Scalar data: ' + data.scalar); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) +### PEDOMETER_DETECTION once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback: Callback<PedometerDetectionResponse>): void @@ -788,15 +766,14 @@ Subscribes to only one data change of the pedometer detection sensor. | callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(data) { console.info('Scalar data: ' + data.scalar); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_PEDOMETER) +### PEDOMETER once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>): void @@ -813,15 +790,14 @@ Subscribes to only one data change of the pedometer sensor. | callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(data) { console.info('Steps: ' + data.steps); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +### AMBIENT_TEMPERATURE once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback: Callback<AmbientTemperatureResponse>): void @@ -836,15 +812,14 @@ Subscribes to only one data change of the ambient temperature sensor. | callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(data) { console.info('Temperature: ' + data.temperature); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) +### MAGNETIC_FIELD once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>): void @@ -859,7 +834,7 @@ Subscribes to only one data change of the magnetic field sensor. | callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -868,8 +843,7 @@ Subscribes to only one data change of the magnetic field sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) +### MAGNETIC_FIELD_UNCALIBRATED once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>): void @@ -884,7 +858,7 @@ Subscribes to only one data change of the uncalibrated magnetic field sensor. | callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -896,8 +870,7 @@ Subscribes to only one data change of the uncalibrated magnetic field sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_PROXIMITY) +### PROXIMITY once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>): void @@ -912,7 +885,7 @@ Subscribes to only one data change of the proximity sensor. | callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); @@ -923,8 +896,7 @@ Subscribes to only one data change of the proximity sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_HUMIDITY) +### HUMIDITY once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>): void @@ -939,15 +911,14 @@ Subscribes to only one data change of the humidity sensor. | callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(data) { console.info('Humidity: ' + data.humidity); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_BAROMETER) +### BAROMETER once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>): void @@ -962,15 +933,14 @@ Subscribes to only one data change of the barometer sensor. | callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { console.info('Atmospheric pressure: ' + data.pressure); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_HALL) +### HALL once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>): void @@ -985,15 +955,14 @@ Subscribes to only one data change of the Hall effect sensor. | callback | Callback<[HallResponse](#hallresponse)> | Yes | One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(data) { console.info('Status: ' + data.status); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) +### AMBIENT_LIGHT once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>): void @@ -1008,15 +977,14 @@ Subscribes to only one data change of the ambient light sensor. | callback | Callback<[LightResponse](#lightresponse)> | Yes | One-shot callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(data) { console.info(' Illumination: ' + data.intensity); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_ORIENTATION) +### ORIENTATION once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>): void @@ -1031,7 +999,7 @@ Subscribes to only one data change of the orientation sensor. | callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(data) { console.info('The device rotates at an angle around the X axis: ' + data.beta); console.info('The device rotates at an angle around the Y axis: ' + data.gamma); @@ -1040,8 +1008,7 @@ Subscribes to only one data change of the orientation sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) +### ROTATION_VECTOR once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: Callback<RotationVectorResponse>): void @@ -1056,7 +1023,7 @@ Subscribes to only one data change of the rotation vector sensor. | callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1066,8 +1033,7 @@ Subscribes to only one data change of the rotation vector sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_HEART_RATE) +### HEART_RATE once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>): void @@ -1084,15 +1050,14 @@ Subscribes to only one data change of the heart rate sensor. | callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, function(data) { console.info("Heart rate: " + data.heartRate); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) +### WEAR_DETECTION once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void @@ -1107,14 +1072,16 @@ Subscribes to only one data change of the wear detection sensor. | callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(data) { console.info("Wear status: "+ data.value); } ); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_ACCELEROMETER) +## sensor.off + +### ACCELEROMETER off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback?: Callback<AccelerometerResponse>): void @@ -1133,7 +1100,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('x-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1142,7 +1109,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) +### ACCELEROMETER_UNCALIBRATED off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback?: Callback<AccelerometerUncalibratedResponse>): void @@ -1161,7 +1128,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1173,7 +1140,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) +### AMBIENT_LIGHT off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback?: Callback<LightResponse>): void @@ -1190,14 +1157,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info(' Illumination: ' + data.intensity); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +### AMBIENT_TEMPERATURE off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatureResponse>): void @@ -1214,14 +1181,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Temperature: ' + data.temperature); } sensor.off( sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +### AMBIENT_TEMPERATURE off(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback?: Callback<BarometerResponse>): void @@ -1238,14 +1205,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Atmospheric pressure: ' + data.pressure); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_GRAVITY) +### GRAVITY off(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback?: Callback<GravityResponse>): void @@ -1262,7 +1229,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1271,7 +1238,7 @@ function callback(data) { sensor.off( sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_GYROSCOPE) +### GYROSCOPE off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback?: Callback<GyroscopeResponse>): void @@ -1290,7 +1257,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1299,7 +1266,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) +### GYROSCOPE_UNCALIBRATED off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void @@ -1318,7 +1285,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1327,7 +1294,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_HALL) +### HALL off(type: SensorType.SENSOR_TYPE_ID_HALL, callback?: Callback<HallResponse>): void @@ -1344,14 +1311,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Status: ' + data.status); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HALL, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_HEART_RATE) +### HEART_RATE off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRateResponse>): void @@ -1370,14 +1337,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info("Heart rate: " + data.heartRate); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_HUMIDITY) +### HUMIDITY off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback<HumidityResponse>): void @@ -1396,14 +1363,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Humidity: ' + data.humidity); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) +### LINEAR_ACCELERATION off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback<LinearAccelerometerResponse>): void @@ -1422,7 +1389,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1431,7 +1398,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) +### MAGNETIC_FIELD off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse>): void @@ -1450,7 +1417,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1459,7 +1426,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) +### MAGNETIC_FIELD_UNCALIBRATED off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticFieldUncalibratedResponse>): void @@ -1476,7 +1443,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1488,7 +1455,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_ORIENTATION) +### ORIENTATION off(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback?: Callback<OrientationResponse>): void @@ -1505,7 +1472,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('The device rotates at an angle around the X axis: ' + data.beta); console.info('The device rotates at an angle around the Y axis: ' + data.gamma); @@ -1514,7 +1481,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_PEDOMETER) +### PEDOMETER off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback?: Callback<PedometerResponse>): void @@ -1529,16 +1496,16 @@ Unsubscribes from sensor data changes. | type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER**. | | callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| -**Return value** +**Example** -``` +```js function callback(data) { console.info('Steps: ' + data.steps); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) +### PEDOMETER_DETECTION off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void @@ -1557,14 +1524,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Scalar data: ' + data.scalar); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_PROXIMITY) +### PROXIMITY off(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback?: Callback<ProximityResponse>): void @@ -1581,14 +1548,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Distance: ' + data.distance); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) +### ROTATION_VECTOR off(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback?: Callback<RotationVectorResponse>): void @@ -1605,7 +1572,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1615,7 +1582,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) +### SIGNIFICANT_MOTION off(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void @@ -1632,14 +1599,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Scalar data: ' + data.scalar); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) +### WEAR_DETECTION off(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback?: Callback<WearDetectionResponse>): void @@ -1656,7 +1623,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function accCallback(data) { console.info('Wear status: ' + data.value); } @@ -1681,13 +1648,13 @@ Rotates a rotation vector so that it can represent the coordinate system in diff **Example** -``` -sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {'axisX':2, 'axisY':3}, function(err, data) { +```js +sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, function(err, data) { if (err) { console.error("Operation failed. Error code: " + err.code + ", message: " + err.message); return; } - console.info("Operation successed. Data obtained: " + data.x); + console.info("Operation successed. Data obtained: " + data); for (var i=0; i < data.length; i++) { console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); } @@ -1716,8 +1683,8 @@ Rotates a rotation vector so that it can represent the coordinate system in diff **Example** -``` -const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {'axisX':2, 'axisY':3}); +```js +const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}); promise.then((data) => { console.info("Operation successed."); for (var i=0; i < data.length; i++) { @@ -1744,8 +1711,8 @@ Obtains the geomagnetic field of a geographic location. This API uses a callback | callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | Yes | Callback used to return the geomagnetic field. | **Example** -``` -sensor.getGeomagneticField([80, 0, 0], 1580486400000, function(err, data) { +```js +sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000, function(err, data) { if (err) { console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); return; @@ -1772,11 +1739,11 @@ Obtains the geomagnetic field of a geographic location. This API uses a promise **Return value** | Type | Description | | ---------------------------------------- | ------- | -| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field.| +| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field. | -**Return value** - ``` - const promise = sensor.getGeomagneticField([80, 0, 0], 1580486400000); +**Example** + ```js + const promise = sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000); promise.then((data) => { console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + @@ -1802,9 +1769,9 @@ Obtains the altitude at which the device is located based on the sea-level atmos | currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa.| | callback | AsyncCallback<number> | Yes | Callback used to return the altitude, in meters. | -**Return value** +**Example** - ``` + ```js sensor.getAltitude(0, 200, function(err, data) { if (err) { console.error( @@ -1836,9 +1803,9 @@ Obtains the altitude at which the device is located based on the sea-level atmos | --------------------- | ------------------ | | Promise<number> | Promise used to return the altitude, in meters.| -**Return value** +**Example** - ``` + ```js const promise = sensor.getAltitude(0, 200); promise.then((data) => { console.info(' sensor_getAltitude_Promise success', data); @@ -1863,12 +1830,12 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a callba | inclinationMatrix | Array<number> | Yes | Inclination matrix. | | callback | AsyncCallback<number> | Yes | Callback used to return the magnetic dip, in radians.| -**Return value** +**Example** - ``` + ```js sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { if (err) { - console.error(LABEL + 'SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + err.message); return; } @@ -1896,9 +1863,9 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a promis | --------------------- | -------------- | | Promise<number> | Promise used to return the magnetic dip, in radians.| -**Return value** +**Example** - ``` + ```js const promise = sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1]); promise.then((data) => { console.info(' getGeomagneticDip_promise successed', data); @@ -1923,18 +1890,18 @@ Obtains the angle change between two rotation matrices. This API uses a callback | preRotationMatrix | Array<number> | Yes | The other rotation matrix. | | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the angle change around the z, x, and y axes.| -**Return value** +**Example** - ``` + ```js sensor. getAngleModify([1,0,0,0,1,0,0,0,1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function(err, data) { if (err) { - console.error(LABEL + 'Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('Failed to register data, error code is: ' + err.code + ', message: ' + err.message); return; } console.info("SensorJsAPI--->Successed to get getAngleModifiy interface get data: " + data.x); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }) ``` @@ -1961,17 +1928,17 @@ Obtains the angle change between two rotation matrices. This API uses a promise | ---------------------------------- | ------------------ | | Promise<Array<number>> | Promise used to return the angle change around the z, x, and y axes.| -**Return value** +**Example** - ``` + ```js const promise = sensor.getAngleModify([1,0,0,0,1,0,0,0,1], [1,0,0,0,0.87,-0.50,0,0.50,0.87]); promise.then((data) => { - console.info(LABEL + 'getAngleModifiy_promise success'); + console.info('getAngleModifiy_promise success'); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }).catch((reason) => { - console.info(LABEL + "promise::catch", reason); + console.info("promise::catch", reason); }) ``` @@ -1991,18 +1958,18 @@ Converts a rotation vector into a rotation matrix. This API uses a callback to r | rotationVector | Array<number> | Yes | Rotation vector to convert.| | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation matrix.| -**Return value** +**Example** - ``` + ```js sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { if (err) { - console.error(LABEL + 'SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + err.message); return; } console.info("SensorJsAPI--->Successed to get createRotationMatrix interface get data: " + data.x); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }) ``` @@ -2028,17 +1995,17 @@ Converts a rotation vector into a rotation matrix. This API uses a promise to re | ---------------------------------- | ------- | | Promise<Array<number>> | Promise used to return the rotation matrix.| -**Return value** +**Example** - ``` + ```js const promise = sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877]); promise.then((data) => { - console.info(LABEL + 'createRotationMatrix_promise success'); + console.info('createRotationMatrix_promise success'); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }).catch((reason) => { - console.info(LABEL + "promise::catch", reason); + console.info("promise::catch", reason); }) ``` @@ -2058,18 +2025,18 @@ Converts a rotation vector into a quaternion. This API uses a callback to return | rotationVector | Array<number> | Yes | Rotation vector to convert.| | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the quaternion. | -**Return value** +**Example** - ``` + ```js sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { if (err) { - console.error(LABEL + 'SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + err.message); return; } console.info("SensorJsAPI--->Successed to get createQuaternion interface get data: " + data.x); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }) ``` @@ -2095,14 +2062,14 @@ Converts a rotation vector into a quaternion. This API uses a promise to return | ---------------------------------- | ------ | | Promise<Array<number>> | Promise used to return the quaternion.| -**Return value** +**Example** - ``` + ```js const promise = sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); promise.then((data) => { console.info('createQuaternion_promise successed'); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }).catch((err) => { console.info('promise failed'); @@ -2125,18 +2092,18 @@ Obtains the device direction based on the rotation matrix. This API uses a callb | rotationMatrix | Array<number> | Yes | Rotation matrix. | | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation angle around the z, x, and y axes.| -**Return value** +**Example** - ``` + ```js sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { if (err) { - console.error(LABEL + 'SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + err.message); return; } - console.info(LABEL + "SensorJsAPI--->Successed to get getDirection interface get data: " + data.x); + console.info("SensorJsAPI--->Successed to get getDirection interface get data: " + data); for (var i = 1; i < data.length; i++) { - console.info(TAG +"sensor_getDirection_callback" + data[i]); + console.info("sensor_getDirection_callback" + data[i]); } }) ``` @@ -2162,14 +2129,14 @@ Obtains the device direction based on the rotation matrix. This API uses a promi | ---------------------------------- | ------------------ | | Promise<Array<number>> | Promise used to return the rotation angle around the z, x, and y axes.| -**Return value** +**Example** - ``` + ```js const promise = sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1]); promise.then((data) => { - console.info(' sensor_getAltitude_Promise success', data.x); + console.info('sensor_getAltitude_Promise success', data); for (var i = 1; i < data.length; i++) { - console.info(TAG +"sensor_getDirection_promise" + data[i]); + console.info("sensor_getDirection_promise" + data[i]); } }).catch((err) => { console.info('promise failed'); @@ -2193,18 +2160,18 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th | geomagnetic | Array<number> | Yes | Geomagnetic vector.| | callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | Yes | Callback used to return the rotation matrix.| -**Return value** +**Example** - ``` + ```js sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(err, data) { if (err) { - console.error(LABEL + 'SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + err.message); return; } console.info("SensorJsAPI--->Successed to get createRotationMatrix interface get data: " + data.x); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]) + console.info("data[" + i + "]: " + data[i]) } }) ``` @@ -2231,17 +2198,17 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th | ---------------------------------------- | ------- | | Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise used to return the rotation matrix.| -**Return value** +**Example** - ``` + ```js const promise = sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); promise.then((data) => { - console.info(LABEL + 'createRotationMatrix_promise successed'); + console.info('createRotationMatrix_promise successed'); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }).catch((err) => { - console.info(LABEL + 'promise failed'); + console.info('promise failed'); }) ``` @@ -2355,11 +2322,11 @@ Describes the orientation sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ------------------------ | +| Name | Type | Readable | Writable | Description | +| ----- | ------ | ---- | ---- | ----------------- | | alpha | number | Yes | Yes | Rotation angle of the device around the z-axis, in degrees.| -| beta | number | Yes | Yes | Rotation angle of the device around the x-axis, in degrees. | -| gamma | number | Yes | Yes | Rotation angle of the device around the y-axis, in degrees. | +| beta | number | Yes | Yes | Rotation angle of the device around the x-axis, in degrees.| +| gamma | number | Yes | Yes | Rotation angle of the device around the y-axis, in degrees.| ## RotationVectorResponse 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 a11942cf16b785967a8491e46a06d8ad820359aa..518167d562ba8801223e206ad5b35ea07ea94936 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,11 +1,17 @@ # ServiceExtensionContext -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. - +> **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**. +## Modules to Import + +``` +import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; +``` ## startAbility @@ -25,13 +31,18 @@ Starts an ability. This API uses a callback to return the result. **Example** ```js - let want = { - "bundleName": "com.example.myapp", - "abilityName": "com.example.myapp.MyAbility" - }; - this.context.startAbility(want, (err) => { - console.log('startAbility result:' + JSON.stringfy(err)); - }); + 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)); + }); + } + } + ``` @@ -58,15 +69,22 @@ Starts an ability. This API uses a promise to return the result. **Example** ```js - let want = { - "bundleName": "com.example.myapp", - "abilityName": "com.example.myapp.MyAbility" - }; - this.context.startAbility(want).then((data) => { - console.log('success:' + JSON.stringfy(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringfy(error)); - }); + 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)); + }); + } + } + + ``` @@ -87,9 +105,16 @@ Terminates this ability. This API uses a callback to return the result. **Example** ```js - this.context.terminateSelf((err) => { - console.log('terminateSelf result:' + JSON.stringfy(err)); - }); + import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; + class MainAbility extends ExtensionContext { + onWindowStageCreate(windowStage) { + this.context.terminateSelf((err) => { + console.log('terminateSelf result:' + JSON.stringify(err)); + }); + } + } + + ``` @@ -110,11 +135,17 @@ Terminates this ability. This API uses a promise to return the result. **Example** ```js - this.context.terminateSelf(want).then((data) => { - console.log('success:' + JSON.stringfy(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringfy(error)); - }); + 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)); + }); + } +} + ``` @@ -144,7 +175,7 @@ Connects this ability to a Service ability. ```js let want = { "bundleName": "com.example.myapp", - "abilityName": "com.example.myapp.MyAbility" + "abilityName": "MyAbility" }; let options = { onConnect: function(elementName, proxy) {}, @@ -173,9 +204,18 @@ Disconnects this ability from the Service ability. This API uses a callback to r **Example** ```js - this.context.disconnectAbility(connection, (err) => { // connection is the return value of connectAbility. - console.log('terminateSelf result:' + JSON.stringfy(err)); - }); + import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; + class MainAbility extends ExtensionContext { + onWindowStageCreate(windowStage) { + let connection=1 + this.context.disconnectAbility(connection, (err) => { + // connection is the return value of connectAbility. + console.log('terminateSelf result:' + JSON.stringify(err)); + }); + } + } + + ``` @@ -202,11 +242,18 @@ Disconnects this ability from the Service ability. This API uses a promise to re **Example** ```js - this.context.disconnectAbility(connection).then((data) => { // connection is the return value of connectAbility. - console.log('success:' + JSON.stringfy(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringfy(error)); - }); + 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. + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-settings.md b/en/application-dev/reference/apis/js-apis-settings.md index 84c909151c43f5420fcb130403a4734db7c54f35..81444a400e5dc33c2a2b53c489488fea4fe1be58 100644 --- a/en/application-dev/reference/apis/js-apis-settings.md +++ b/en/application-dev/reference/apis/js-apis-settings.md @@ -1,6 +1,6 @@ # Settings -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE**
> The initial APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. @@ -23,21 +23,24 @@ Obtains the URI of a data item. **System capability**: SystemCapability.Applictaions.settings.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | name | string | Yes| Name of the target data item. Data items can be classified as follows:
  • Existing data items in the database, for example:
    • Brightness: 'settings.screen.brightness'
    • Time format: 'settings.time.format'
  • Custom data items
| +**Parameters** -- Return value - | Type| Description| - | -------- | -------- | - | string | URI of the data item.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of the target data item. Data items can be classified as follows:
  • Existing data items in the database, for example:
    • Brightness: settings.display.SCREEN_BRIGHTNESS_STATUS
    • Time format: settings.date.TIME_FORMAT
  • Custom data items
| -- Example - ```typescript - // Obtain the URI of a data item. - let urivar = settings.getUriSync('settings.screen.brightness'); - ``` +**Return value** + +| Type| Description| +| -------- | -------- | +| string | URI of the data item.| + +**Example** + +```typescript + // Obtain the URI of a data item. + let urivar = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); +``` ## settings.getValueSync @@ -48,28 +51,29 @@ Obtains the value of a data item. **System capability**: SystemCapability.Applictaions.settings.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes| **DataAbilityHelper** class.| - | name | string | Yes| Name of the target data item. Data items can be classified as follows:
  • Existing data items in the database, for example:
    • Brightness: 'settings.screen.brightness'
    • Time format: 'settings.time.format'
  • Custom data items
| - | defValue | string | Yes| Default value This parameter is user-defined. If it is not found in the database, the default value is returned.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes| **DataAbilityHelper** class.| +| name | string | Yes| Name of the target data item. Data items can be classified as follows:
  • Existing data items in the database, for example:
    • Brightness: settings.display.SCREEN_BRIGHTNESS_STATUS
    • Time format: settings.date.TIME_FORMAT
  • Custom data items
| +| defValue | string | Yes| Default value This parameter is user-defined. If it is not found in the database, the default value is returned.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | Value of the data item.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Value of the data item.| +**Example** -- Example - ```typescript +```typescript import featureAbility from '@ohos.ability.featureAbility'; - // Obtain the value of 'settings.screen.brightness' (this data item already exists in the database). - let brightness = 'settings.screen.brightness'; - let uri = settings.getUriSync(brightness); - let helper = featureAbility.acquireDataAbilityHelper(uri); - let value = settings.getValueSync(helper, brightness, '10'); - ``` +// Obtain the value of settings.display.SCREEN_BRIGHTNESS_STATUS (this data item already exists in the database). +let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); +let helper = featureAbility.acquireDataAbilityHelper(uri); +let value = settings.getValueSync(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '10'); +``` ## settings.setValueSync @@ -77,32 +81,35 @@ Obtains the value of a data item. setValueSync(dataAbilityHelper: DataAbilityHelper, name: string, value: string): boolean Sets the value of a data item. + If the specified data item exists in the database, the **setValueSync** method updates the value of the data item. If the data item does not exist in the database, the **setValueSync** method inserts the data item into the database. -**Required permissions**: ohos.permission.WRITE_SYSTEM_SETTING +**Required permissions**: ohos.permission.MODIFY_SETTINGS **System capability**: SystemCapability.Applictaions.settings.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes| **DataAbilityHelper** class.| - | name | string | Yes| Name of the target data item. Data items can be classified as follows:
  • Existing data items in the database, for example:
    • Brightness: 'settings.screen.brightness'
    • Time format: 'settings.time.format'
  • Custom data items
| - | value | string | Yes| Value of the data item.| +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes| **DataAbilityHelper** class.| +| name | string | Yes| Name of the target data item. Data items can be classified as follows:
  • Existing data items in the database, for example:
    • Brightness: settings.display.SCREEN_BRIGHTNESS_STATUS
    • Time format: settings.date.TIME_FORMAT
  • Custom data items
| +| value | string | Yes| Value of the data item.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Result indicating whether the value is set successfully. Returns **true** if the value is set successfully; returns **false** otherwise.| +**Return value** -- Example - ```typescript +| Type| Description| +| -------- | -------- | +| boolean | Result indicating whether the value is set successfully. Returns **true** if the value is set successfully; returns **false** otherwise.| + +**Example** + +```typescript import featureAbility from '@ohos.ability.featureAbility'; - // Update the value of 'settings.screen.brightness'. (As this data item exists in the database, the setValueSync - method will update the value of the data item.) - let brightness = 'settings.screen.brightness'; - let uri = settings.getUriSync(brightness); - let helper = featureAbility.acquireDataAbilityHelper(uri); - let ret = settings.setValueSync(helper, brightness, '100'); - ``` +// Update the value of settings.display.SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValueSync + method will update the value of the data item.) +let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); +let helper = featureAbility.acquireDataAbilityHelper(uri); +let ret = settings.setValueSync(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100'); +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index f1f20e8d810c3f3fa648e680d494199e30bc1dfe..3344e47d14f8d615b1f81e75f92251dc4e8c8287 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -521,7 +521,7 @@ Obtains the number of card slots. **Example** ```js -console.log(sim.getMaxSimCount()) +console.log("Result: "+ sim.getMaxSimCount()) ``` diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index 85e8f3f411ea91289ecfcb410eae43b6ea4e57b6..a264817ec018ad6a7fe22888ea0f7a3c5f223fcf 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -6,13 +6,13 @@ ## Modules to Import -```js +``` import sms from '@ohos.telephony.sms'; ``` ## sms.createMessage -createMessage\(pdu: Array, specification: string, callback: AsyncCallback\): void +createMessage\(pdu: Array<number>, specification: string, callback: AsyncCallback\): void Creates an SMS message instance based on the protocol data unit (PDU) and the specified SMS protocol. This API uses an asynchronous callback to return the result. @@ -28,7 +28,7 @@ Creates an SMS message instance based on the protocol data unit (PDU) and the sp **Example** -```js +``` const specification = '3gpp'; // Display PDUs using numbers in an array, for example, [0x08, 0x91, ...]. const pdu = [0x08, 0x91]; @@ -40,7 +40,7 @@ sms.createMessage(pdu, specification, (err, data) => { ## sms.createMessage -createMessage\(pdu: Array, specification: string\): Promise +createMessage\(pdu: Array<number>, specification: string\): Promise Creates an SMS message instance based on the PDU and the specified SMS protocol. This API uses a promise to return the result. @@ -61,7 +61,7 @@ Creates an SMS message instance based on the PDU and the specified SMS protocol. **Example** -```js +``` const specification = '3gpp'; // Display PDUs using numbers in an array, for example, [0x08, 0x91, ...]. const pdu = [0x08, 0x91]; @@ -91,7 +91,7 @@ Sends an SMS message. **Example** -```js +``` let sendCallback = function (err, data) { console.log(`sendCallback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); } @@ -110,7 +110,7 @@ sms.sendMessage(options); ## sms.getDefaultSmsSlotId7+ -getDefaultSmsSlotId\(callback: AsyncCallback\): void +getDefaultSmsSlotId\(callback: AsyncCallback<number>\): void Obtains the default slot of the SIM card used to send SMS messages. This API uses an asynchronous callback to return the result. @@ -124,7 +124,7 @@ Obtains the default slot of the SIM card used to send SMS messages. This API use **Example** -```js +``` sms.getDefaultSmsSlotId((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -133,7 +133,7 @@ sms.getDefaultSmsSlotId((err, data) => { ## sms.getDefaultSmsSlotId7+ -getDefaultSmsSlotId\(\): Promise +getDefaultSmsSlotId\(\): Promise<number> Obtains the default slot of the SIM card used to send SMS messages. This API uses a promise to return the result. @@ -143,11 +143,11 @@ Obtains the default slot of the SIM card used to send SMS messages. This API use | Type | Description | | --------------- | ------------------------------------------------------------ | -| Promise | Promise used to return the result.
- **0**: card slot 1
- **1**: card slot 2| +| Promise<number> | Promise used to return the result.
- **0**: card slot 1
- **1**: card slot 2| **Example** -```js +``` let promise = sms.getDefaultSmsSlotId(); promise.then(data => { console.log(`getDefaultSmsSlotId success, promise: data->${JSON.stringify(data)}`); @@ -179,7 +179,7 @@ This is a system API and cannot be called by third-party applications. **Example** -```js +``` let slotId = 0; let smscAddr = '+861xxxxxxxxxx'; sms.setSmscAddr(slotId, smscAddr, (err,data) => { @@ -215,7 +215,7 @@ This is a system API and cannot be called by third-party applications. **Example** -```js +``` let slotId = 0; let smscAddr = '+861xxxxxxxxxx'; let promise = sms.setSmscAddr(slotId, smscAddr); @@ -248,7 +248,7 @@ This is a system API and cannot be called by third-party applications. **Example** -```js +``` let slotId = 0; sms.getSmscAddr(slotId, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -282,7 +282,7 @@ This is a system API and cannot be called by third-party applications. **Example** -```js +``` let slotId = 0; let promise = sms.getSmscAddr(slotId); promise.then(data => { @@ -306,7 +306,7 @@ Checks whether the current device can send and receive SMS messages. This API wo | ------- | ------------------------------------------------------------ | | boolean | - **true**: The device can send and receive SMS messages.
- **false**: The device cannot send or receive SMS messages.| -```js +``` let result = sms.hasSmsCapability(); console.log(`hasSmsCapability: ${JSON.stringify(result)}`); ``` @@ -319,7 +319,7 @@ Defines an SMS message instance. | Name | Type | Description | | ------------------------ | --------------------------------------- | ------------------------------------------------------------ | -| hasReplyPath | boolean | Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.
**TP-Reply-Path**: the path in which the mobile phone can reply to the SMS message through the originating SMSC.| +| hasReplyPath | boolean | Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.
**TP-Reply-Path**: the path in which the device can reply to the SMS message through the originating SMSC.| | isReplaceMessage | boolean | Whether the received SMS message is a **replace short message**. The default value is **false**.
For details, see section 9.2.3.9 in **3GPP TS 23.040**.| | isSmsStatusReportMessage | boolean | Whether the received SMS message is an SMS delivery status report. The default value is **false**.
**SMS-Status-Report**: a message sent from the SMSC to the mobile station to show the SMS message delivery status.| | messageClass | [ShortMessageClass](#shortmessageclass) | SMS message type. | @@ -390,7 +390,7 @@ Provides the callback for the SMS message sending result. Return the SMS deliver ## SendSmsResult -SMS message sending result. +Enumerates SMS message sending results. **System capability**: SystemCapability.Telephony.SmsMms diff --git a/en/application-dev/reference/apis/js-apis-stack.md b/en/application-dev/reference/apis/js-apis-stack.md index 245f4f88fd48e8b3b3ba2263e67fe0a33e95959b..b1e10e9478bc3335b30cd85498f9feb81b07bfd1 100644 --- a/en/application-dev/reference/apis/js-apis-stack.md +++ b/en/application-dev/reference/apis/js-apis-stack.md @@ -1,28 +1,33 @@ # Linear Container Stack -> ![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. +**Stack** is implemented based on the array data structure. It follows the principle Last Out First In (LOFI) and supports data insertion and removal at one end. + +Unlike **[Queue](js-apis-queue.md)**, which is implemented based on the queue data structure and supports insertion at one end and removal at the other end, **Stack** supports insertion and removal at the same end. + +**Recommended use case**: Use **Stack** in LOFI scenarios. ## Modules to Import ```ts -import Stack from '@ohos.util.Stack' +import Stack from '@ohos.util.Stack'; ``` -## System Capabilities -SystemCapability.Utils.Lang ## Stack - ### Attributes +**System capability**: SystemCapability.Utils.Lang + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Number of entries in a stack (called container later).| +| length | number | Yes| No| Number of elements in a stack (called container later).| ### constructor @@ -31,6 +36,8 @@ constructor() A constructor used to create a **Stack** instance. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -42,13 +49,15 @@ let stack = new Stack(); push(item: T): T -Adds an entry at the top of this container. +Adds an element at the top of this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| item | T | Yes| Element to add.| +| item | T | Yes| Target element.| **Return value** @@ -72,13 +81,15 @@ let result3 = stack.push(c); pop(): T -Removes the top entry from this container. +Removes the top element from this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Type| Description| | -------- | -------- | -| T | Entry removed.| +| T | Element removed.| **Example** @@ -96,13 +107,15 @@ let result = stack.pop(); peek(): T -Obtains the top entry of this container. +Obtains the top element of this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Type| Description| | -------- | -------- | -| T | Entry obtained.| +| T | Element obtained.| **Example** @@ -119,19 +132,21 @@ let result = stack.peek(); locate(element: T): number -Obtains the index of the first occurrence of the specified entry in this container. +Obtains the index of the first occurrence of the specified element in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to query.| +| element | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| number | Returns the position index if obtained; returns **-1** if the specified entry is not found.| +| number | Returns the position index if obtained; returns **-1** otherwise.| **Example** @@ -149,21 +164,23 @@ let result = stack.locate(2); forEach(callbackfn: (value: T, index?: number, stack?: Stack<T>) => void, thisArg?: Object): void -Uses a callback to traverse the entries in this container and obtain their position indexes. +Uses a callback to traverse the elements in this container and obtain their position indexes. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.| +| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Value of the entry that is currently traversed.| -| index | number | No| Position index of the entry that is currently traversed.| +| value | T | Yes| Value of the element that is currently traversed.| +| index | number | No| Position index of the element that is currently traversed.| | stack | Stack<T> | No| Instance that invokes the **forEach** method.| **Example** @@ -175,7 +192,7 @@ stack.push(4); stack.push(5); stack.push(4); stack.forEach((value, index) => { - console.log(value, index); + console.log("value:" + value, index); }); ``` @@ -183,7 +200,9 @@ stack.forEach((value, index) => { isEmpty(): boolean -Checks whether this container is empty (contains no entries). +Checks whether this container is empty (contains no elements). + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -206,9 +225,10 @@ let result = stack.isEmpty(); [Symbol.iterator]\(): IterableIterator<T> - Obtains an iterator, each item of which is a JavaScript object. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -225,14 +245,14 @@ stack.push(4); // Method 1: for (let item of stack) { - console.log(item); + console.log("value:" + item); } // Method 2: let iter = stack[Symbol.iterator](); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value:" + temp); temp = iter.next().value; } ``` 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 6a5ee3a36ab94c810f6ef9cc720ded250445f3de..a0b973cb896a595e5361d5a441ab184bf0339b3d 100644 --- a/en/application-dev/reference/apis/js-apis-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-storage-statistics.md @@ -1,9 +1,11 @@ # App Storage Statistics -> ![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. -> - API version 9 is a canary release for trial use. The APIs of this version may be unstable. +> - API version 9 is a canary version for trial use. The APIs of this version may be unstable. + +Obtains 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 @@ -15,10 +17,14 @@ import storagestatistics from "@ohos.storageStatistics"; getTotalSizeOfVolume(volumeUuid: string): Promise<number> -Asynchronously obtains the total space of the specified volume. This API uses a promise to return the result. +Asynchronously obtains the total size of the specified volume. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics +**System API**: This is a system API and cannot be called by third-party applications. + - Parameters | Name | Type | Mandatory| Description| @@ -29,7 +35,7 @@ Asynchronously obtains the total space of the specified volume. This API uses a | Type | Description | | --------------------- | ---------------- | - | Promise<number> | Promise used to return the total space of the volume.| + | Promise<number> | Promise used to return the total size of the volume.| - Example @@ -46,16 +52,20 @@ Asynchronously obtains the total space of the specified volume. This API uses a getTotalSizeOfVolume(volumeUuid: string, callback:AsyncCallback<number>):void -Asynchronously obtains the total space of the specified volume. This API uses a callback to return the result. +Asynchronously obtains the total size of the specified volume. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics +**System API**: This is a system API and cannot be called by third-party applications. + - Parameters | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | -------------------------- | | volumeUuid | string | Yes | UUID of the volume. | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total space of the volume.| + | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total size of the volume.| - Example @@ -75,8 +85,12 @@ getFreeSizeOfVolume(volumeUuid: string): Promise<number> Asynchronously obtains the available space of the specified volume. This API uses a promise to return the result. +**Required permissions**: ohos.permission.STORAGE_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics +**System API**: This is a system API and cannot be called by third-party applications. + - Parameters | Name | Type | Mandatory| Description| @@ -107,8 +121,12 @@ getFreeSizeOfVolume(volumeUuid: string, callback:AsyncCallback<number>):vo Asynchronously obtains the available space of the specified volume. This API uses a callback to return the result. +**Required permissions**: ohos.permission.STORAGE_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics +**System API**: This is a system API and cannot be called by third-party applications. + - Parameters | Name | Type | Mandatory| Description | @@ -130,21 +148,25 @@ Asynchronously obtains the available space of the specified volume. This API use getBundleStats(packageName: string): Promise<BundleStats> -Asynchronously obtains app information. This API uses a promise to return the result. +Asynchronously obtains space information of an application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics +**System API**: This is a system API and cannot be called by third-party applications. + - Parameters | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | -------- | - | packageName | string | Yes | Bundle name of the app.| + | packageName | string | Yes | Bundle name of the application.| - Return value | Type | Description | | ------------------------------------------ | -------------------------- | - | Promise<[Bundlestats](#bundlestats)> | Promise used to return the app information.| + | Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained.| - Example @@ -161,16 +183,20 @@ Asynchronously obtains app information. This API uses a promise to return the re getBundleStats(packageName: string, callback: AsyncCallback<BundleStats>): void -Asynchronously obtains app information. This API uses a callback to return the result. +Asynchronously obtains space information of an application. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics +**System API**: This is a system API and cannot be called by third-party applications. + - Parameters | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | - | packageName | string | Yes | Bundle name of the app.| - | callback | callback:AsyncCallback<[Bundlestats](#bundlestats)> | Yes | Callback invoked to return the app information.| + | packageName | string | Yes | Bundle name of the application.| + | callback | callback:AsyncCallback<[Bundlestats](#bundlestats)> | Yes | Callback invoked to return the space information obtained.| - Example @@ -182,14 +208,310 @@ Asynchronously obtains app information. This API uses a callback to return the r }); ``` + + +## storagestatistics.getCurrentBundleStats9+ + +getCurrentBundleStats(): Promise + +Asynchronously obtains space information of the current third-party application. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + +- Return value + + | Type | Description | + | ------------------------------------------ | -------------------------- | + | Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained. | + +- Example + + ```js + let bundleStats = await storageStatistics.getCurrentBundleStats(); + console.info("getCurrentBundleStats successfully:"+ JSON.stringify(bundleStats)); + ``` + +## storagestatistics.getCurrentBundleStats9+ + +getCurrentBundleStats(callback: AsyncCallback): void + +Asynchronously obtains space information of the current third-party application. This API uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + +- Parameters + + | Name | Type | Mandatory | Description | + | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | + | callback | callback:AsyncCallback<[BundleStats](#bundlestats)> | Yes | Callback invoked to return the space information obtained. | + +- Example + + ```js + storagestatistics.getCurrentBundleStats(function(error, bundleStats){ + // Do something. + console.info("getCurrentBundleStats successfully:"+ JSON.stringify(bundleStats)); + }); + ``` + + + ## BundleStats9+ **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -### Attributes +- Attributes + +| Name | Type | Description | +| --------- | ------ | -------------- | +| appSize | number | Size of the application. | +| cacheSize | number | Cache size of the application. | +| dataSize | number | Total data size of the application.| + + + + +## storagestatistics.getTotalSize9+ + +getTotalSize(): Promise + +Obtains the total space of the built-in memory card. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + +**System API**: This is a system API and cannot be called by third-party applications. + +- Return value + + | Type | Description | + | --------------------- | ------------------ | + | Promise<number> | Promise used to return the total space of the built-in memory card. | + +- Example + + ```js + let number = await storageStatistics.getTotalSize(); + console.info("getTotalSize successfully:"+ JSON.stringify(number)); + ``` + +## storagestatistics.getTotalSize9+ + +getTotalSize(callback: AsyncCallback): void + +Obtains the total space of the built-in memory card. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + +**System API**: This is a system API and cannot be called by third-party applications. + +- Parameters + + | Name | Type | Mandatory | Description | + | -------- | ------------------------------------ | ---- | ------------------------ | + | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total space of the built-in memory card.| + +- Example + + ```js + storagestatistics.getTotalSize(function(error, number){ + // Do something. + console.info("getTotalSize successfully:"+ JSON.stringify(number)); + }); + ``` + + +## storagestatistics.getFreeSize9+ + +getFreeSize(): Promise + +Obtains the available space of the built-in memory card. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + +**System API**: This is a system API and cannot be called by third-party applications. + +- Return value + + | Type | Description | + | --------------------- | ------------------ | + | Promise<number> | Promise used to return the available space of the built-in memory card.| + +- Example + + ```js + let number = await storageStatistics.getFreeSize(); + console.info("getFreeSize successfully:"+ JSON.stringify(number)); + ``` + + +## storagestatistics.getFreeSize9+ + +getFreeSize(callback: AsyncCallback): void + +Obtains the available space of the built-in memory card. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + +**System API**: This is a system API and cannot be called by third-party applications. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------ | ---- | ------------------------- | + | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the built-in memory card.| + +- Example + + ```js + storagestatistics.getFreeSize(function(error, number){ + // Do something. + console.info("getFreeSize successfully:"+ JSON.stringify(number)); + }); + ``` + + + +## storagestatistics.getSystemSize9+ + +getSystemSize(): Promise<number> + +Asynchronously obtains the system space. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + +**System API**: This is a system API and cannot be called by third-party applications. + +- Return value + + | Type | Description | + | --------------------- | ---------------- | + | Promise<number> | Promise used to return the system space obtained.| + +- Example + + ```js + storagestatistics.getSystemSize().then(function(number){ + console.info("getSystemSize successfully:"+ number); + }).catch(function(err){ + console.info("getSystemSize failed with error:"+ err); + }); + ``` + +## storagestatistics.getSystemSize9+ + +getSystemSize(callback:AsyncCallback<number>):void + +Asynchronously obtains the system space. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + +**System API**: This is a system API and cannot be called by third-party applications. + +- Parameters + + | Name | Type | Mandatory| Description | + | ---------- | ------------------------------------ | ---- | -------------------------- | + | callback | callback:AsyncCallback<number> | Yes | Callback used to return the system space obtained.| + +- Example + + ```js + storagestatistics.getSystemSize(function(error, number){ + // Do something. + console.info("getSystemSize successfully:"+ number); + }); + ``` + + + +## storagestatistics.getUserStorageStats9+ + +getUserStorageStats(userId?: string): Promise<StorageStats> + +Asynchronously obtains the space occupied by each type of user data. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + +**System API**: This is a system API and cannot be called by third-party applications. + +- Parameters + + | Name | Type | Mandatory| Description| + | ---------- | ------ | ---- | ---- | + | userId | string | No | User ID.
-  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 + + | Type | Description | + | --------------------- | ---------------- | + | Promise<[StorageStats](#StorageStats)> | Promise used to return the information obtained.| + +- Example + + ```js + let userId = ""; + storagestatistics.getUserStorageStats(userId).then(function(StorageStats){ + console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats)); + }).catch(function(err){ + console.info("getUserStorageStats failed with error:"+ err); + }); + ``` + +## storagestatistics.getUserStorageStats9+ + +getUserStorageStats(userId?: string, callback:AsyncCallback<StorageStats>):void + +Asynchronously obtains the space occupied by each type of user data. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + +**System API**: This is a system API and cannot be called by third-party applications. + +- Parameters + + | Name | Type | Mandatory| Description | + | ---------- | ------------------------------------ | ---- | -------------------------- | + | userId | string | No | User ID.
-  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 + storagestatistics.getUserStorageStats(userId, function(error, StorageStats){ + // Do something. + console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats)); + }); + ``` + + + +## StorageStats9+ + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + +- Attributes | Name | Type | Description | | --------- | ------ | -------------- | -| appSize9+ | number | Size of the app. | -| cacheSize9+ | number | Cache size of the app. | -| dataSize9+ | number | Total data size of the app.| +| total | number | Total space of the built-in memory card. | +| audio | number | Space occupied by audio data. | +| video | number | Space occupied by video data.| +| image | number | Space occupied by image data. | +| file | number | Space occupied by files. | +| app | number | Space occupied by application data.| diff --git a/en/application-dev/reference/apis/js-apis-system-cipher.md b/en/application-dev/reference/apis/js-apis-system-cipher.md index b0dc3c5b117f5256020aa0cc5073e662c62cb6c9..2cc2fa8e75d563784bfc31efcb919619b5738994 100644 --- a/en/application-dev/reference/apis/js-apis-system-cipher.md +++ b/en/application-dev/reference/apis/js-apis-system-cipher.md @@ -1,15 +1,14 @@ # Encryption Algorithm -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> **NOTE**
> -> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. +> The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import cipher from '@system.cipher' ``` @@ -24,27 +23,27 @@ Encrypts or decrypts data using RSA. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | string | Yes | Action type. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data. | -| text | string | Yes | Text content to be encrypted or decrypted. The text to be encrypted must be a common text and cannot exceed the length calculated based on the formula (keySize/8 - 66). **keySize** indicates the key length. For example, if the key length is 1024 bytes, the text cannot exceed 62 bytes (1024/8 - 66 = 62). The text content to be decrypted must be a binary value encoded using Base64. The default format is used for Base64 encoding. | -| key | string | Yes | Keys encrypted using RSA. During encryption, this parameter is a public key. During decryption, it is a private key. | -| transformation | string | No | RSA algorithm padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**. | -| success | Function | No | Called when data is encrypted or decrypted successfully. | -| fail | Function | No | Called when data fails to be encrypted or decrypted. | -| complete | Function | No | Called when the execution is complete. | +| action | string | Yes| Action to perform. The options are as follows:
- encrypt
- decrypt| +| text | string | Yes| Text to be encrypted or decrypted.
The text to be encrypted must be common text that meets the following requirement:
Maximum text length = Key length/8 - 66
For example, if the key is of 1024 bytes, the text to be encrypted cannot exceed 62 bytes (1024/8 -66 = 62).
The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| +| key | string | Yes| RSA key. The key is used as a public key in encryption and a private key in decryption.| +| transformation | string | No| RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.| +| success | Function | No| Called when data is encrypted or decrypted successful.| +| fail | Function | No| Called when data fails to be encrypted or decrypted.| +| complete | Function | No| Called when the execution is complete.| **Example** -``` +```js export default { rsa() { cipher.rsa({ - // Encrypt data. + // Encrypt data. action: 'encrypt', - // Text content to be encrypted + // Text to be encrypted. text: 'hello', - // Base64-encoded public key used for encryption + // Base64-encoded public key used for encryption. key: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDc7GR2MrfAoefES+wrs1ns2afT\n' + 'eJXSfIkEHfPXG9fVFjaws1ho4KcZfsxlA0+SXvc83f2SVGCuzULmM2lxxRCtcUN/\n' + @@ -58,14 +57,14 @@ export default { } }); cipher.rsa({ - // Decrypt data. + // Decrypt data. action: 'decrypt', - // The text to be decrypted is a Base64-encoded binary value, and the decrypted text is "hello". + // Text to be decrypted, which is binary text encoded in Base64. The decrypted text is "hello". text: 'CUg3tTxTIdpCfreIxIBdws3uhd5qXLwcrVl3XDnQzZFVHyjVVCDHS16rjopaZ4C5xU2Tc8mSDzt7\n' + 'gp9vBfSwi7bMtSUvXG18DlncsKJFDkJpS5t0PkpS9YrJXrY80Gpe+ME6+6dN9bjgqMljbitDdBRf\n' + 'S/ZWNI4Q8Q0suNjNkGU=', - // Base64-encoded public key used for encryption + // Base64-encoded private key used for decryption. key: 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANzsZHYyt8Ch58RL\n' + '7CuzWezZp9N4ldJ8iQQd89cb19UWNrCzWGjgpxl+zGUDT5Je9zzd/ZJUYK7NQuYz\n' + @@ -103,30 +102,30 @@ Encrypts or decrypts data using AES. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | string | Yes | Action type. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data. | -| text | string | Yes | Text content to be encrypted or decrypted. The text to be encrypted must be a common text. The text content to be decrypted must be a binary value encoded using Base64. The default format is used for Base64 encoding. | -| key | string | Yes | Key used for encryption or decryption, which is a character string encrypted using Base64. | -| transformation | string | No | Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**. | -| iv | string | No | Initial vector for AES-based encryption and decryption. The value is a character string encoded using Base64. The default value is the key value. | -| ivOffset | string | No | Offset of the initial vector for AES-based encryption and decryption. The default value is **0**. | -| ivLen | string | No | Length of the initial vector for AES-based encryption and decryption. The default value is **16**. | -| success | Function | No | Called when data is encrypted or decrypted successfully. | -| fail | Function | No | Called when data fails to be encrypted or decrypted. | -| complete | Function | No | Called when the execution is complete. | +| action | string | Yes| Action to perform. The options are as follows:
- encrypt
- decrypt| +| text | string | Yes| Text to be encrypted or decrypted.
The text to be encrypted must be common text. The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| +| key | string | Yes| Key used for encryption or decryption. It is a string encoded in Base64.| +| transformation | string | No| Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**.| +| iv | string | No| Initialization vector (IV) for AES-based encryption and decryption. The value is a string encoded in Base64. The default value is the key value.| +| ivOffset | string | No| Offset of the IV for AES-based encryption and decryption. The default value is **0**.| +| ivLen | string | No| Length of the IV for AES-based encryption and decryption, in bytes. The default value is **16**.| +| success | Function | No| Called when data is encrypted or decrypted successful.| +| fail | Function | No| Called when data fails to be encrypted or decrypted.| +| complete | Function | No| Called when the execution is complete.| **Example** -``` +```js export default { aes() { cipher.aes({ - // Encrypt data. + // Encrypt data. action: 'encrypt', - // Text content to be encrypted + // Text to be encrypted. text: 'hello', - // Base64-encoded key used for encryption + // Base64-encoded key used for encryption. key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', transformation: 'AES/CBC/PKCS5Padding', ivOffset: 0, @@ -139,13 +138,13 @@ export default { } }); cipher.aes({ - // Decrypt data. + // Decrypt data. action: 'decrypt', - // Text to be decrypted, which is a Base64-encoded binary value + // Text to be decrypted, which is binary text encoded in Base64. text: 'CUg3tTxTIdpCfreIxIBdws3uhd5qXLwcrVl3XDnQzZFVHyjVVCDHS16rjopaZ4C5xU2Tc8mSDzt7\n' + 'gp9vBfSwi7bMtSUvXG18DlncsKJFDkJpS5t0PkpS9YrJXrY80Gpe+ME6+6dN9bjgqMljbitDdBRf\n' + 'S/ZWNI4Q8Q0suNjNkGU=', - // Base64-encoded key used for decryption + // Base64-encoded key used for decryption. key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', transformation: 'AES/CBC/PKCS5Padding', ivOffset: 0, @@ -162,4 +161,4 @@ export default { } } -``` \ No newline at end of file +``` diff --git a/en/application-dev/reference/apis/js-apis-system-parameter.md b/en/application-dev/reference/apis/js-apis-system-parameter.md index c068d0429fcd2aa1ee91fb3dd145ee32296274e8..999c894303b070539e3fdc5c4010aaa0a5f19803 100644 --- a/en/application-dev/reference/apis/js-apis-system-parameter.md +++ b/en/application-dev/reference/apis/js-apis-system-parameter.md @@ -1,7 +1,6 @@ # System Parameter > **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. > - This is a system API and cannot be called by third-party applications. @@ -49,7 +48,7 @@ try { get(key: string, callback: AsyncCallback<string>): void -Obtains the value of the attribute with the specified key. +Obtains the value of the attribute with the specified key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Startup.SysInfo @@ -80,7 +79,7 @@ try { get(key: string, def: string, callback: AsyncCallback<string>): void -Obtains the value of the attribute with the specified key. +Obtains the value of the attribute with the specified key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Startup.SysInfo @@ -89,7 +88,7 @@ Obtains the value of the attribute with the specified key. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the system attribute.| -| def | string | Yes| Default Value| +| def | string | Yes| Default value.| | callback | AsyncCallback<string> | Yes| Callback used to return the result.| **Example** @@ -113,7 +112,7 @@ try { get(key: string, def?: string): Promise<string> -Obtains the value of the attribute with the specified key. +Obtains the value of the attribute with the specified key. This API uses a promise to return the result. **System capability**: SystemCapability.Startup.SysInfo @@ -122,7 +121,7 @@ Obtains the value of the attribute with the specified key. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the system attribute.| -| def | string | No| Default Value| +| def | string | No| Default value.| **Return value** @@ -176,7 +175,7 @@ try { set(key: string, value: string, callback: AsyncCallback<void>): void -Sets a value for the attribute with the specified key. +Sets a value for the attribute with the specified key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Startup.SysInfo @@ -208,7 +207,7 @@ try { set(key: string, value: string): Promise<void> -Sets a value for the attribute with the specified key. +Sets a value for the attribute with the specified key. This API uses a promise to return the result. **System capability**: SystemCapability.Startup.SysInfo @@ -217,7 +216,7 @@ Sets a value for the attribute with the specified key. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the system attribute.| -| value| string | Yes| System attribute value to set.| +| value| string | Yes | System attribute value to set.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-system-prompt.md b/en/application-dev/reference/apis/js-apis-system-prompt.md index f894715391f015cbd67ecf913a7923c00d4e78e1..e37601dbfa3ec72d13a7722fb4dc56a8b3fe6fef 100644 --- a/en/application-dev/reference/apis/js-apis-system-prompt.md +++ b/en/application-dev/reference/apis/js-apis-system-prompt.md @@ -1,8 +1,8 @@ # Prompt -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** > -> - The APIs of this module are no longer maintained since API version 8. You are advised to use ['@ohos.prompt](js-apis-prompt.md)' instead. +> - The APIs of this module are no longer maintained since API version 8. You are advised to use [`@ohos.prompt`](js-apis-prompt.md) instead. > > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -11,7 +11,7 @@ ## Modules to Import -``` +```js import prompt from '@system.prompt'; ``` @@ -31,7 +31,7 @@ Shows the toast. **Example** -``` +```js export default { showToast() { prompt.showToast({ @@ -60,7 +60,7 @@ Shows the dialog box. **Example** -``` +```js export default { showDialog() { prompt.showDialog({ @@ -100,7 +100,7 @@ Shows the action menu. **Example** -``` +```js export default { showActionMenu() { prompt.showActionMenu({ @@ -115,11 +115,11 @@ export default { color: '#000000', }, ], - success: function(data) { + success: function(tapIndex) { console.log('dialog success callback, click button : ' + data.tapIndex); }, - fail: function(data) { - console.log('dialog fail callback' + data.errMsg); + fail: function(errMsg) { + console.log('dialog fail callback' + errMsg); }, }); } @@ -135,7 +135,7 @@ Describes the options for showing the toast. | ------------------- | -------------- | ---- | ---------------------------------------- | | message | string | Yes | Text to display. | | duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The recommended value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used.| -| bottom5+ | string\|number | No | Distance between the toast frame and the bottom of the screen. This parameter is available only on phones and tablets. | +| bottom5+ | string\|number | No | Distance between the toast border and the bottom of the screen. | ## Button diff --git a/en/application-dev/reference/apis/js-apis-system-router.md b/en/application-dev/reference/apis/js-apis-system-router.md index a93ffdfa68f6406c6290221d4c5fe757fd7c906b..0f1f932efe54af1337ce19354d19343b6f637687 100644 --- a/en/application-dev/reference/apis/js-apis-system-router.md +++ b/en/application-dev/reference/apis/js-apis-system-router.md @@ -1,6 +1,6 @@ # Page Routing -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** > > - The APIs of this module are no longer maintained since API version 8. You are advised to use [`@ohos.router`](js-apis-router.md) instead. > @@ -11,7 +11,7 @@ ## Modules to Import -``` +```js import router from '@system.router'; ``` @@ -31,7 +31,7 @@ Navigates to a specified page in the application. **Example** -``` +```js // Current page export default { pushPage() { @@ -49,7 +49,7 @@ export default { ``` -``` +```js // routerpage2 page export default { data: { @@ -85,7 +85,7 @@ Replaces the current page with another one in the application and destroys the c **Example** -``` +```js // Current page export default { replacePage() { @@ -100,7 +100,7 @@ export default { ``` -``` +```js // detail page export default { data: { @@ -128,7 +128,7 @@ Returns to the previous page or a specified page. **Example** -``` +```js // index page export default { indexPushPage() { @@ -140,7 +140,7 @@ export default { ``` -``` +```js // detail page export default { detailPushPage() { @@ -152,7 +152,7 @@ export default { ``` -``` +```js // Navigate from the mall page to the detail page through router.back(). export default { mallBackPage() { @@ -162,7 +162,7 @@ export default { ``` -``` +```js // Navigate from the detail page to the index page through router.back(). export default { defaultBack() { @@ -172,7 +172,7 @@ export default { ``` -``` +```js // Return to the detail page through router.back(). export default { backToDetail() { @@ -208,7 +208,7 @@ Clears all historical pages in the stack and retains only the current page at th **Example** -``` +```js export default { clearPage() { router.clear(); @@ -232,7 +232,7 @@ Obtains the number of pages in the current stack. **Example** -``` +```js export default { getLength() { var size = router.getLength(); @@ -257,7 +257,7 @@ Obtains state information about the current page. **Example** -``` +```js export default { getState() { var page = router.getState(); @@ -284,7 +284,7 @@ Enables the display of a confirm dialog box before returning to the previous pag **Example** -``` +```js export default { enableAlertBeforeBackPage() { router.enableAlertBeforeBackPage({ @@ -292,8 +292,8 @@ export default { success: function() { console.log('success'); }, - fail: function() { - console.log('fail'); + cancel: function() { + console.log('cancel'); }, }); } @@ -316,15 +316,15 @@ Disables the display of a confirm dialog box before returning to the previous pa **Example** -``` +```js export default { disableAlertBeforeBackPage() { router.disableAlertBeforeBackPage({ success: function() { console.log('success'); }, - fail: function() { - console.log('fail'); + cancel: function() { + console.log('cancel'); }, }); } diff --git a/en/application-dev/reference/apis/js-apis-system-storage.md b/en/application-dev/reference/apis/js-apis-system-storage.md index 37e8dc5de76e930a81a337c9afd3fe0adcd459c4..ffa96a8e8e6f569c7cc2b9413736aff7048d7713 100644 --- a/en/application-dev/reference/apis/js-apis-system-storage.md +++ b/en/application-dev/reference/apis/js-apis-system-storage.md @@ -68,7 +68,7 @@ Sets the value in the cache based on the specified key. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the data to set.| -| value | string | Yes| New value to set. The maximum length is 128 bytes.| +| value | string | Yes| New value to set. The length must be less than 128 bytes.| | success | Function | No| Called when **storage.set()** is successful.| | fail | Function | No| Called when **storage.set()** fails. In the callback, **data** indicates the error information, and **code** indicates the error code.| | complete | Function | No| Called when **storage.set()** is complete.| diff --git a/en/application-dev/reference/apis/js-apis-system-time.md b/en/application-dev/reference/apis/js-apis-system-time.md index 74beca3c0aacbabd628f99f7987b96caf5988f61..9d8abc5a6a73f95e4a1c674fc1c1a716154f56d8 100644 --- a/en/application-dev/reference/apis/js-apis-system-time.md +++ b/en/application-dev/reference/apis/js-apis-system-time.md @@ -1,7 +1,8 @@ # Setting the System Time -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. -> +This module provides the time, time zone, and timing services. Use the time and time zone services to set and obtain the system time and time zone, and use the timing service to manage and use the system time and time zone to implement alarms or other timing functions. + +> **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 @@ -199,7 +200,7 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This ## systemTime.getRealTime8+ -getRealTime(callback: AsyncCallback<number>): void +getRealTime(isNano?: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since system start, including the deep sleep time. This API uses an asynchronous callback to return the result. @@ -227,7 +228,7 @@ Obtains the time elapsed since system start, including the deep sleep time. This ## systemTime.getRealTime8+ -getRealTime(): Promise<number> +getRealTime(isNano?: boolean): Promise<number> Obtains the time elapsed since system start, including the deep sleep time. This API uses a promise to return the result. diff --git a/en/application-dev/reference/apis/js-apis-timer.md b/en/application-dev/reference/apis/js-apis-timer.md index a7265c4972c52318d2f624939e935e56abdb2e63..d144a95db8f59ca0605fd228b351380afe6feac8 100644 --- a/en/application-dev/reference/apis/js-apis-timer.md +++ b/en/application-dev/reference/apis/js-apis-timer.md @@ -1,261 +1,126 @@ -# Timer +# Timer ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->The initial APIs of this module are supported since API version 4. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## Module to Import +## setTimeout -None +## Modules to Import -## Required Permissions -None +``` +import Time from '@ohos.Time'; +``` -## setTimeout - -setTimeout\(handler\[,delay\[, ...args\]\]\): number +setTimeout(handler[,delay[,…args]]): number Sets a timer for the system to call a function after the timer goes off. -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

handler

-

Function

-

Yes

-

Function to be called after the timer goes off.

-

delay

-

number

-

No

-

Number of milliseconds delayed before the execution. If this parameter is left empty, the default value 0 is used, which means that the execution starts immediately or as soon as possible.

-

...args

-

Array<any>

-

No

-

Additional parameter to pass to the handler after the timer goes off.

-
- -- Return Value - - - - - - - - - - -

Type

-

Description

-

number

-

Timer ID.

-
- -- Example - - ``` - export default { - setTimeOut() { - var timeoutID = setTimeout(function() { - console.log('delay 1s'); - }, 1000); - } - } - ``` - - -## clearTimeout - -clearTimeout\(timeoutID: number\): void - -Cancels the timer created via **setTimeout\(\)**. - -- Parameter - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

timeoutID

-

number

-

Yes

-

ID of the timer to cancel, which is returned by setTimeout()

-
- -- Example - - ``` - export default { - clearTimeOut() { - var timeoutID = setTimeout(function() { - console.log('do after 1s delay.'); - }, 1000); - clearTimeout(timeoutID); - } - } - ``` - - -## setInterval - -setInterval\(handler\[, delay\[, ...args\]\]\): number +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| handler | Function | Yes| Function to be called after the timer goes off.| +| delay | number | No| Number of milliseconds delayed before the execution. If this parameter is left empty, the default value **0** is used, which means that the execution starts immediately or as soon as possible.| +| ...args | Array<any> | No| Additional parameters to pass to the handler after the timer goes off.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Timer ID.| + +**Example** + +```js +export default { + setTimeOut() { + var timeoutID = setTimeout(function() { + console.log('delay 1s'); + }, 1000); + } +} +``` + + +## clearTimeout + +clearTimeout(timeoutID: number): void + +Cancels the timer created via **setTimeout()**. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| timeoutID | number | Yes| ID of the timer to cancel, which is returned by **setTimeout()**| + +**Example** + +```js +export default { + clearTimeOut() { + var timeoutID = setTimeout(function() { + console.log('do after 1s delay.'); + }, 1000); + clearTimeout(timeoutID); + } +} +``` + + +## setInterval + +setInterval(handler[, delay[, ...args]]): number Sets a repeating timer for the system to repeatedly call a function at a fixed interval. -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

handler

-

Function

-

Yes

-

Function to be called repeatedly

-

delay

-

number

-

No

-

Number of milliseconds delayed before the execution

-

...args

-

Array<any>

-

No

-

Additional parameter to pass to the handler after the timer goes off

-
- -- Return Value - - - - - - - - - - -

Type

-

Description

-

number

-

ID of the repeated timer.

-
- -- Example - - ``` - export default { - setInterval() { - var intervalID = setInterval(function() { - console.log('do very 1s.'); - }, 1000); - } - } - ``` - - -## clearInterval - -clearInterval\(intervalID: number\): void - -Cancels the repeating timer set via **setInterval\(\)**. - -- Parameter - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

intervalID

-

number

-

Yes

-

ID of the repeating timer to cancel, which is returned by setInterval().

-
- -- Example - - ``` - export default { - clearInterval() { - var intervalID = setInterval(function() { - console.log('do very 1s.'); - }, 1000); - clearInterval(intervalID); - } - } - ``` +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| handler | Function | Yes| Function to be called repeatedly.| +| delay | number | No| Number of milliseconds delayed before the execution.| +| ...args | Array<any> | No| Additional parameters to pass to the handler after the timer goes off.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | ID of the repeating timer.| + +**Example** + +```js +export default { + setInterval() { + var intervalID = setInterval(function() { + console.log('do very 1s.'); + }, 1000); + } +} +``` + + +## clearInterval + +clearInterval(intervalID: number): void + +Cancels the repeating timer set via **setInterval()**. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| intervalID | number | Yes| ID of the repeating timer to cancel, which is returned by **setInterval()**.| +**Example** +```js +export default { + clearInterval() { + var intervalID = setInterval(function() { + console.log('do very 1s.'); + }, 1000); + clearInterval(intervalID); + } +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-touchevent.md b/en/application-dev/reference/apis/js-apis-touchevent.md new file mode 100644 index 0000000000000000000000000000000000000000..05a6e52c9d6f1e402dc9a7e3d8d4a19c9a117ec3 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-touchevent.md @@ -0,0 +1,84 @@ +# Touch Event + +Represents touch events reported by an input 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 + +```js +import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput.touchEvent'; +``` + +## Action + +**System capability**: SystemCapability.MultimodalInput.Input.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| CANCEL | number | Yes| No| Cancellation of the touch action.| +| DOWN | number | Yes| No| Pressing of touch.| +| MOVE | number | Yes| No| Moving of touch.| +| UP | number | Yes| No| Lifting of touch.| + +## ToolType + +**System capability**: SystemCapability.MultimodalInput.Input.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| FINGER | number | Yes| No| Finger| +| PEN | number | Yes| No| Pen| +| RUBBER | number | Yes| No| Eraser| +| BRUSH | number | Yes| No| Brush| +| PENCIL | number | Yes| No| Pencil| +| AIRBRUSH | number | Yes| No| Air brush| +| MOUSE | number | Yes| No| Mouse| +| LENS | number | Yes| No| Lens| + +## SourceType + +**System capability**: SystemCapability.MultimodalInput.Input.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| TOUCH_SCREEN | number | Yes| No| Touchscreen| +| PEN | number | Yes| No| Stylus| +| TOUCH_PAD | number | Yes| No| Touchpad| + +## Touch + +**System capability**: SystemCapability.MultimodalInput.Input.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| id | number | Yes| No| Pointer ID.| +| pressedTime | number | Yes| No| Time stamp when touch is pressed.| +| screenX | number | Yes| No| X coordinate of the touch position on the screen.| +| screenY | number | Yes| No| Y coordinate of the touch position on the screen.| +| windowX | number | Yes| No| X coordinate of the touch position in the window.| +| windowY | number | Yes| No| Y coordinate of the touch position in the window.| +| pressure | number | Yes| No| Pressure value. The value range is [0.0, 1.0]. The value 0.0 indicates that the pressure is not supported.| +| width | number | Yes| No| Width of the contact area where touch is pressed.| +| height | number | Yes| No| Height of the contact area where touch is pressed.| +| tiltX | number | Yes| No| Angle relative to the YZ plane. The value range is [-90, 90]. A positive value indicates a rightward tilt.| +| tiltY | number | Yes| No| Angle relative to the XZ plane. The value range is [-90, 90]. A positive value indicates a downward tilt.| +| toolX | number | Yes| No| Center point X of the tool area.| +| toolY | number | Yes| No| Center point Y of the tool area.| +| toolWidth | number | Yes| No| Width of the tool area.| +| toolHeight | number | Yes| No| Height of the tool area.| +| rawX | number | Yes| No| X coordinate of the input device.| +| rawY | number | Yes| No| Y coordinate of the input device.| +| toolType | number | Yes| No| Tool type.| + +## TouchEvent + +**System capability**: SystemCapability.MultimodalInput.Input.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| action | Action | Yes| No| Touch action.| +| touch | Touch | Yes| No| Current touch point.| +| touches | Touch[] | Yes| No| All touch points.| +| sourceType | SourceType | Yes| No| Device type of the touch source.| diff --git a/en/application-dev/reference/apis/js-apis-treemap.md b/en/application-dev/reference/apis/js-apis-treemap.md index c3d62b882dbb74012ba561135f5934dae3b3e22e..7914e5bd409d29b3bcae14653aaa6bd8dd5f6f9c 100644 --- a/en/application-dev/reference/apis/js-apis-treemap.md +++ b/en/application-dev/reference/apis/js-apis-treemap.md @@ -1,27 +1,32 @@ # Nonlinear Container TreeMap -> ![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. +**TreeMap** stores key-value (KV) pairs. Each key must be unique and have only one value. + +**TreeMap** is implemented using a red-black tree, which is a binary search tree where keys are stored in sorted order for efficient insertion and removal. + +**[HashMap](js-apis-treemap.md)** is faster in accessing data than **TreeMap**, because the former accesses data based on the hash code of the key, whereas the latter stores and accesses the keys in sorted order. + +Recommended use case: Use **TreeMap** when you need to store KV pairs in sorted order. ## Modules to Import ```ts -import TreeMap from '@ohos.util.TreeMap' +import TreeMap from '@ohos.util.TreeMap'; ``` -## System Capabilities - -SystemCapability.Utils.Lang - ## TreeMap - ### Attributes +**System capability**: SystemCapability.Utils.Lang + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Number of entries in a tree map (called container later).| +| length | number | Yes| No| Number of elements in a tree map (called container later).| ### constructor @@ -30,6 +35,8 @@ constructor(comparator?:(firstValue: K, secondValue: K) => boolean) A constructor used to create a **TreeMap** instance. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| @@ -47,7 +54,9 @@ let treeMap = new TreeMap(); isEmpty(): boolean -Checks whether this container is empty (contains no entry). +Checks whether this container is empty (contains no element). + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -69,11 +78,13 @@ hasKey(key: K): boolean Checks whether this container has the specified key. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key to check.| +| key | K | Yes| Target key.| **Return value** @@ -97,11 +108,13 @@ hasValue(value: V): boolean Checks whether this container has the specified value. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | Yes| Value to check.| +| value | V | Yes| Target value.| **Return value** @@ -125,11 +138,13 @@ get(key: K): V Obtains the value of the specified key in this container. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key to query.| +| key | K | Yes| Target key.| **Return value** @@ -153,6 +168,8 @@ getFirstKey(): K Obtains the first key in this container. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -175,6 +192,8 @@ getLastKey(): K Obtains the last key in this container. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -195,13 +214,15 @@ let result = treeMap.getLastKey(); setAll(map: TreeMap): void -Adds all entries in a **TreeMap** instance to this container. +Adds all elements in a **TreeMap** instance to this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| map | TreeMap | Yes| **TreeMap** instance whose entries are to be added to the current container.| +| map | TreeMap | Yes| **TreeMap** instance whose elements are to be added to the current container.| **Example** @@ -218,20 +239,22 @@ treeMap.setAll(map); set(key: K, value: V): Object -Adds an entry to this container. +Adds an element to this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key of the entry to add.| -| value | V | Yes| Value of the entry to add.| +| key | K | Yes| Key of the target element.| +| value | V | Yes| Value of the target element.| **Return value** | Type| Description| | -------- | -------- | -| Object | Container that contains the new entry.| +| Object | Container that contains the new element.| **Example** @@ -245,19 +268,21 @@ treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); remove(key: K): V -Removes the entry with the specified key from this container. +Removes the element with the specified key from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key of the entry to remove.| +| key | K | Yes| Target key.| **Return value** | Type| Description| | -------- | -------- | -| V | Value of the entry removed.| +| V | Value of the element removed.| **Example** @@ -275,6 +300,8 @@ getLowerKey(key: K): K Obtains the key that is placed in front of the input key in this container. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| @@ -304,6 +331,8 @@ getHigherKey(key: K): K Obtains the key that is placed next to the input key in this container. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| @@ -330,20 +359,22 @@ let result = treeMap.getHigherKey("sdfs"); replace(key: K, newValue: V): boolean -Replaces an entry in this container. +Replaces an element in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key of the entry to replace.| -| newValue | V | Yes| New value of the entry.| +| key | K | Yes| Key of the target element.| +| newValue | V | Yes| New value of the element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the entry is replaced successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is replaced successfully; returns **false** otherwise.| **Example** @@ -360,6 +391,8 @@ clear(): void Clears this container and sets its length to **0**. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -376,6 +409,8 @@ keys(): IterableIterator<K> Obtains an iterator that contains all the keys in this container. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -391,7 +426,7 @@ treeMap.set("sdfs", 356); let iter = treeMap.keys(); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value:" + temp); temp = iter.next().value; } ``` @@ -403,6 +438,8 @@ values(): IterableIterator<V> Obtains an iterator that contains all the values in this container. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -418,7 +455,7 @@ treeMap.set("sdfs", 356); let iter = treeMap.values(); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value:" + temp); temp = iter.next().value; } ``` @@ -428,20 +465,22 @@ while(temp != undefined) { forEach(callbackfn: (value?: V, key?: K, map?: TreeMap) => void, thisArg?: Object): void -Uses a callback to traverse the entries in this container and obtain their position indexes. +Uses a callback to traverse the elements in this container and obtain their position indexes. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.| +| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | No| Value of the entry that is currently traversed.| -| key | K | No| Key of the entry that is currently traversed.| +| value | V | No| Value of the element that is currently traversed.| +| key | K | No| Key of the element that is currently traversed.| | map | TreeMap | No| Instance that invokes the **forEach** method.| **Example** @@ -451,7 +490,7 @@ let treeMap = new TreeMap(); treeMap.set("sdfs", 123); treeMap.set("dfsghsf", 357); treeMap.forEach((value, key) => { - console.log(value, key); + console.log("value:" + value, key); }); ``` @@ -460,7 +499,9 @@ treeMap.forEach((value, key) => { entries(): IterableIterator<[K, V]> -Obtains an iterator that contains all the entries in this container. +Obtains an iterator that contains all the elements in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -477,8 +518,8 @@ treeMap.set("sdfs", 356); let iter = treeMap.entries(); let temp = iter.next().value; while(temp != undefined) { - console.log(temp[0]); - console.log(temp[1]); + console.log("key:" + temp[0]); + console.log("value:" + temp[1]); temp = iter.next().value; } ``` @@ -488,9 +529,10 @@ while(temp != undefined) { [Symbol.iterator]\(): IterableIterator<[K, V]> - Obtains an iterator, each item of which is a JavaScript object. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| | -------- | -------- | @@ -505,16 +547,16 @@ treeMap.set("sdfs", 356); // Method 1: for (let item of treeMap) { - console.log("key: " + item[0]); - console.log("value: " + item[1]); + console.log("key:" + item[0]); + console.log("value:" + item[1]); } // Method 2: let iter = treeMap[Symbol.iterator](); let temp = iter.next().value; while(temp != undefined) { - console.log(temp[0]); - console.log(temp[1]); + console.log("key:" + temp[0]); + console.log("value:" + temp[1]); temp = iter.next().value; } ``` diff --git a/en/application-dev/reference/apis/js-apis-treeset.md b/en/application-dev/reference/apis/js-apis-treeset.md index 4c535ab446abcb7ad2e6f5dc0e7956b3ab8b88b2..6e50abcf23c7cf2c3a77e6029244a0078edd1562 100644 --- a/en/application-dev/reference/apis/js-apis-treeset.md +++ b/en/application-dev/reference/apis/js-apis-treeset.md @@ -1,27 +1,30 @@ # Nonlinear Container TreeSet -> ![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. +**TreeSet** is implemented based on **[TreeMap](js-apis-treemap.md)**. In **TreeSet**, only **value** objects are processed. **TreeSet** can be used to store values, each of which must be unique. + +**[HashSet](js-apis-hashset.md)** stores data in a random order, whereas **TreeSet** stores data in sorted order. Both of them allows only unique elements. However, null values are allowed in **HashSet**, but not allowed in **TreeSet**. + +Recommended use case: Use **TreeSet** when you need to store data in sorted order. ## Modules to Import ```ts -import TreeSet from '@ohos.util.TreeSet' +import TreeSet from '@ohos.util.TreeSet'; ``` -## System Capabilities - -SystemCapability.Utils.Lang - ## TreeSet - ### Attributes +**System capability**: SystemCapability.Utils.Lang + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Number of entries in a tree set (called container later).| +| length | number | Yes| No| Number of elements in a tree set (called container later).| ### constructor @@ -30,6 +33,8 @@ constructor(comparator?:(firstValue: T, secondValue: T) => boolean) A constructor used to create a **TreeSet** instance. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| @@ -47,7 +52,9 @@ let treeSet = new TreeSet(); isEmpty(): boolean -Checks whether this container is empty (contains no entry). +Checks whether this container is empty (contains no element). + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -69,11 +76,13 @@ has(value: T): boolean Checks whether this container has the specified value. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Value to query.| +| value | T | Yes| Target value.| **Return value** @@ -95,7 +104,9 @@ let result1 = treeSet.has(123); getFirstValue(): T -Obtains the value of the first entry in this container. +Obtains the value of the first element in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -117,7 +128,9 @@ let result = treeSet.getFirstValue(); getLastValue(): T -Obtains the value of the last entry in this container. +Obtains the value of the last element in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -139,19 +152,21 @@ let result = treeSet.getLastValue(); add(value: T): boolean -Adds an entry to this container. +Adds an element to this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Entry to add.| +| value | T | Yes| Target element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the entry is added successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is added successfully; returns **false** otherwise.| **Example** @@ -165,19 +180,21 @@ let result = treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); remove(value: T): boolean -Removes the entry with the specified key from this container. +Removes the element with the specified key from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Key of the entry to remove.| +| value | T | Yes| Key of the target element.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the entry is removed successfully; returns **false** otherwise.| +| boolean | Returns **true** if the element is removed successfully; returns **false** otherwise.| **Example** @@ -195,6 +212,8 @@ getLowerValue(key: T): T Obtains the value that is placed in front of the input key in this container. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| @@ -224,6 +243,8 @@ getHigherValue(key: T): T Obtains the value that is placed next to the input key in this container. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name| Type| Mandatory| Description| @@ -251,15 +272,17 @@ let result = treeSet.getHigherValue("sdfs"); popFirst(): T -Removes the first entry in this container. +Removes the first element in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Type| Description| | -------- | -------- | -| T | Entry removed.| +| T | Element removed.| -**Return value** +**Example** ```ts let treeSet = new TreeSet(); @@ -273,15 +296,17 @@ let result = treeSet.popFirst(); popLast(): T -Removes the last entry in this container. +Removes the last element in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Type| Description| | -------- | -------- | -| T | Entry removed.| +| T | Element removed.| -**Return value** +**Example** ```ts let treeSet = new TreeSet(); @@ -297,6 +322,8 @@ clear(): void Clears this container and sets its length to **0**. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -313,6 +340,8 @@ values(): IterableIterator<T> Obtains an iterator that contains all the values in this container. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -328,7 +357,7 @@ treeSet.add("sdfs"); let iter = treeSet.values(); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value:" + temp); temp = iter.next().value; } ``` @@ -338,20 +367,22 @@ while(temp != undefined) { forEach(callbackfn: (value?: T, key?: T, set?: TreeSet<T>) => void, thisArg?: Object): void -Uses a callback to traverse the entries in this container and obtain their position indexes. +Uses a callback to traverse the elements in this container and obtain their position indexes. + +**System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.| +| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | No| Value of the entry that is currently traversed.| -| key | T | No| Key of the entry that is currently traversed (same as **value**).| +| value | T | No| Value of the element that is currently traversed.| +| key | T | No| Key of the element that is currently traversed (same as **value**).| | set | TreeSet<T> | No| Instance that invokes the **forEach** method.| **Example** @@ -361,7 +392,7 @@ let treeSet = new TreeSet(); treeSet.add("sdfs"); treeSet.add("dfsghsf"); treeSet.forEach((value, key) => { - console.log(value, key) + console.log("value:" + value, key) }); ``` @@ -370,7 +401,9 @@ treeSet.forEach((value, key) => { entries(): IterableIterator<[T, T]> -Obtains an iterator that contains all the entries in this container. +Obtains an iterator that contains all the elements in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -387,8 +420,8 @@ treeSet.add("sdfs"); let iter = treeSet.entries(); let temp = iter.next().value; while(temp != undefined) { - console.log(temp[0]); - console.log(temp[1]); + console.log("key:" + temp[0]); + console.log("value:" + temp[1]); temp = iter.next().value; } ``` @@ -398,9 +431,10 @@ while(temp != undefined) { [Symbol.iterator]\(): IterableIterator<T> - Obtains an iterator, each item of which is a JavaScript object. +**System capability**: SystemCapability.Utils.Lang + **Return value** | Type| Description| @@ -416,14 +450,14 @@ treeSet.add("sdfs"); // Method 1: for (let item of treeSet) { - console.log("value: " + item); + console.log("value:" + item); } // Method 2: let iter = treeSet[Symbol.iterator](); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value:" + temp); temp = iter.next().value; } ``` diff --git a/en/application-dev/reference/apis/js-apis-uitest.md b/en/application-dev/reference/apis/js-apis-uitest.md index b554e47f481696c48dea31a47315e454a01b9efa..6586d6f0a2c7fc5641a5b49411f67390859e3bfe 100644 --- a/en/application-dev/reference/apis/js-apis-uitest.md +++ b/en/application-dev/reference/apis/js-apis-uitest.md @@ -1,8 +1,7 @@ # UiTest ->**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. > ->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 @@ -13,46 +12,27 @@ import {UiDriver,BY,MatchPattern} from '@ohos.uitest' ## By -The UiTest framework provides a wide range of UI component feature description APIs in the **By** class to filter and match components. -The API capabilities provided by the **By** class exhibit the following features: +The UiTest framework provides a wide range of UI component feature description APIs in the **By** class to filter and match components.
+The API capabilities provided by the **By** class exhibit the following features:
1. Allow one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component.
2. Provide multiple match patterns for component attributes.
3. Support absolute positioning and relative positioning for components. APIs such as [By.isBefore](#byisbefore) and [By.isAfter](#byisafter) can be used to specify the features of adjacent components to assist positioning.
All APIs provided in the **By** class are synchronous. You are advised to use the static constructor **BY** to create a **By** object in chain mode. -- Allows one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component. - -- Provides multiple match patterns for component attributes. - -- Supports absolute positioning and relative positioning for components. APIs such as **isBefore** and **isAfter** can be used to specify the features of adjacent components to assist positioning. - -All APIs provided in the **By** class are synchronous. You are advised to use the static constructor **BY** to create a **By** object in chain mode, for example, **BY.text('123').type('button')**. - -### enum MatchPattern - -Enumerates the match patterns supported for component attributes. - -**System capability**: SystemCapability.Test.UiTest - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| EQUALS | 0 | Equal to the given value. | -| CONTAINS | 1 | Contain the given value. | -| STARTS_WITH | 2 | Start with the given value.| -| ENDS_WITH | 3 | End with the given value.| +```js +BY.text('123').type('button') +``` ### By.text -text(txt:string,pattern?:MatchPattern):By +text(txt: string, pattern?: MatchPattern): By Specifies the text attribute of the target component. Multiple match patterns are supported. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------ | ---- | ---------------------------------- | -| txt | string | Yes | Component text, used to match the target component.| -| pattern | MatchPattern | No | Match pattern. The default value is **EQUALS**. | +| Name | Type | Mandatory| Description | +| ------- | ------------ | ---- | ------------------------------------------------- | +| txt | string | Yes | Component text, used to match the target component. | +| pattern | MatchPattern | No | Match pattern. The default value is [EQUALS](#matchpattern).| **Return value** @@ -62,324 +42,382 @@ Specifies the text attribute of the target component. Multiple match patterns ar **Example** -``` -let by = BY.text('123') // Use the static constructor BY to create a By object and specify the text attribute - of the target component. +```js +let by = BY.text('123') // Use the static constructor BY to create a By object and specify the text attribute of the target component. ``` ### By.key -key(key:string):By; +key(key: string): By Specifies the key attribute of the target component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | --------------- | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------- | | key | string | Yes | Component key.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.key('123') // Use the static constructor BY to create a By object and specify the key attribute - of the target component. +```js +let by = BY.key('123') // Use the static constructor BY to create a By object and specify the key attribute of the target component. ``` ### By.id -id(id:number):By; - -Specifies the ID property of the target component. +id(id: number): By -**Required permissions**: none +Specifies the ID attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------ | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | | id | number | Yes | Component ID.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.id(123) // Use the static constructor BY to create a By object and specify the ID attribute - of the target component. +```js +let by = BY.id(123) // Use the static constructor BY to create a By object and specify the id attribute of the target component. ``` ### By.type -type(tp:string):By; +type(tp: string): By -Specifies the type property of the target component. - -**Required permissions**: none +Specifies the type attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------ | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------- | | tp | string | Yes | Component type.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.type('button') // Use the static constructor BY to create a By object and specify the type attribute - of the target component. +```js +let by = BY.type('button') // Use the static constructor BY to create a By object and specify the type attribute of the target component. ``` ### By.clickable -clickable(b?:bool):By; +clickable(b?: bool): By Specifies the clickable attribute of the target component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------------------- | | b | bool | No | Clickable status of the target component. The default value is **true**.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** +```js +let by = BY.clickable(true) // Use the static constructor BY to create a By object and specify the clickable status attribute of the target component. ``` -let by = BY.clickable(true) // Use the static constructor BY to create a By object and specify the clickable attribute - of the target component. + +### By.longClickable9+ + +longClickable(b?: bool): By + +Specifies the long-clickable status attribute of the target component. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------------------------ | +| b | bool | No | Long-clickable status of the target component. The default value is **true**.| + +**Return value** + +| Type| Description | +| ---- | ---------------- | +| By | Returns the **By** object itself.| + +**Example** + +```js +let by = BY.longClickable(true) // Use the static constructor BY to create a By object and specify the long-clickable status attribute of the target component. ``` ### By.scrollable -scrollable(b?:bool):By; +scrollable(b?: bool): By -Specifies the scrollable attribute of the target component. - -**Required permissions**: none +Specifies the scrollable status attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | -------------------------- | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------------------- | | b | bool | No | Scrollable status of the target component. The default value is **true**.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.scrollable(true) // Use the static constructor BY to create a By object and specify the scrollable attribute - of the target component. +```js +let by = BY.scrollable(true) // Use the static constructor BY to create a By object and specify the scrollable status attribute of the target component. ``` ### By.enabled -enabled(b?:bool):By; - -Specifies the enable attribute of the target component. +enabled(b?: bool): By -**Required permissions**: none +Specifies the enabled status attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ---------------------------- | -| b | bool | No | Enable status of the target component. The default value is **true**.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------------------ | +| b | bool | No | Enabled status of the target component. The default value is **true**.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.enabled(true) // Use the static constructor BY to create a By object and specify the enable attribute - of the target component. +```js +let by = BY.enabled(true) // Use the static constructor BY to create a By object and specify the enabled status attribute of the target component. ``` ### By.focused -focused(b?:bool):By; - -Specifies the focused attribute of the target component. +focused(b?: bool): By -**Required permissions**: none +Specifies the focused status attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------------- | | b | bool | No | Focused status of the target component. The default value is **true**.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.enabled(true) // Use the static constructor BY to create a By object and specify the focused attribute - of the target component. +```js +let by = BY.focused(true) // Use the static constructor BY to create a By object and specify the focused status attribute of the target component. ``` ### By.selected -selected(b?:bool):By; - -Specifies the selected attribute of the target component. +selected(b?: bool): By -**Required permissions**: none +Specifies the selected status attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------------------- | | b | bool | No | Selected status of the target component. The default value is **true**.| **Return value** +| Type| Description | +| ---- | ---------------- | +| By | Returns the **By** object itself.| + +**Example** + +```js +let by = BY.selected(true) // Use the static constructor BY to create a By object and specify the selected status attribute of the target component. +``` + +### By.checked9+ + +checked(b?: bool): By + +Specifies the checked status attribute of the target component. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | --------------------------------- | +| b | bool | No | Checked status of the target component. The default value is **false**.| + +**Return value** + | Type| Description | | ---- | -------------- | | By | Returns the **By** object itself.| **Example** +```js +let by = BY.checked(true) // Use the static constructor BY to create a By object and specify the checked status attribute of the target component. ``` -let by = BY.selected(true) // Use the static constructor BY to create a By object and specify the selected attribute - of the target component. + +### By.checkable9+ + +checkable(b?: bool): By + +Specifies the checkable status attribute of the target component. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------------------------- | +| b | bool | No | Checkable status of the target component. The default value is **false**.| + +**Return value** + +| Type| Description | +| ---- | ---------------- | +| By | Returns the **By** object itself.| + +**Example** + +```js +let by = BY.checkable(true) // Use the static constructor BY to create a By object and specify the checkable status attribute of the target component. ``` ### By.isBefore -isBefore(by:By):By; +isBefore(by: By): By Specifies the attributes of the component before which the target component is located. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | -------------- | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------- | | by | By | Yes | Attributes of the component before which the target component is located.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.isBefore(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes - of the component before which the target component is located. +```js +let by = BY.isBefore(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes of the component before which the target component is located. ``` ### By.isAfter -isAfter(by:By):By; +isAfter(by: By): By Specifies the attributes of the component after which the target component is located. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | -------------- | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------- | | by | By | Yes | Attributes of the component before which the target component is located.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.isAfter(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes - of the component after which the target component is located. +```js +let by = BY.isAfter(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes of the component after which the target component is located. ``` ## UiComponent In **UiTest**, the **UiComponent** class represents a component on the UI and provides APIs for obtaining component attributes, clicking a component, scrolling to search for a component, and text injection. -All APIs provided by this class use a promise to return the result and must be invoked using **await**. +All APIs provided in this class use a promise to return the result and must be invoked using **await**. + +### Rect9+ + +Provides border information of a component. + +**System capability**: SystemCapability.Test.UiTest + +| Name | Type| Readable| Writable| Description | +| ------- | -------- | ---- | ---- | ------------------------- | +| leftX | number | Yes | No | X coordinate of the upper left corner of the component borders.| +| topY | number | Yes | No | Y coordinate of the upper left corner of the component borders.| +| rightX | number | Yes | No | X coordinate of the lower right corner of the component borders.| +| bottomY | number | Yes | No | Y coordinate of the lower right corner of the component borders.| ### UiComponent.click -click():Promise; +click(): Promise\ Clicks this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -389,37 +427,33 @@ async function demo() { ### UiComponent.doubleClick -doubleClick():Promise; +doubleClick(): Promise\ Double-clicks this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) - await buttont.doubleClick() + await button.doubleClick() } ``` ### UiComponent.longClick -longClick():Promise; +longClick(): Promise\ Long-clicks this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -429,23 +463,21 @@ async function demo() { ### UiComponent.getId -getId():Promise; +getId(): Promise\ Obtains the ID of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| ---------------- | ------------------------- | -| Promise; | Promise used to return the component ID.| +| Type | Description | +| ---------------- | ------------------------------- | +| Promise\ | Promise used to return the ID of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -455,23 +487,21 @@ async function demo() { ### UiComponent.getKey -getKey():Promise; +getKey(): Promise\ Obtains the key of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| ---------------- | -------------------------- | -| Promise; | Promise used to return the component key.| +| Type | Description | +| ---------------- | ------------------------------ | +| Promise\ | Promise used to return the key of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -481,23 +511,21 @@ async function demo() { ### UiComponent.getText -getText():Promise; +getText(): Promise\ Obtains the text information of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| ---------------- | ------------------------------- | -| Promise; | Promise used to return the text information of the component.| +| Type | Description | +| ---------------- | --------------------------------- | +| Promise\ | Promise used to return the text information of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -507,23 +535,21 @@ async function demo() { ### UiComponent.getType -getType():Promise; +getType(): Promise\ Obtains the type of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| ---------------- | ------------------------------- | -| Promise; | Promise used to return the component type.| +| Type | Description | +| ---------------- | ----------------------------- | +| Promise\ | Promise used to return the type of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -531,25 +557,47 @@ async function demo() { } ``` +### UiComponent.getBounds9+ + +getBounds(): Promise\ + +Obtains the bounds of this component. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the bounds of the component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + let rect = await button.getBounds() +} +``` + ### UiComponent.isClickable -isClickable():Promise; +isClickable(): Promise\ Obtains the clickable status of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | ----------------------------------- | -| Promise; | Promise used to return the clickable status of the component.| +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the clickable status of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -562,25 +610,110 @@ async function demo() { } ``` -### UiComponent.isScrollable +### UiComponent.isLongClickable9+ -isScrollable():Promise; +isLongClickable(): Promise\ -Obtains the scrollable status of this component. +Obtains the long clickable status of this component. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------------- | +| Promise\ | Promise used to return the long clickable status of the component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + if(await button.isLongClickable()) { + console.info('This button can longClick') + } + else{ + console.info('This button can not longClick') + } +} +``` + +### UiComponent.isChecked9+ + +isChecked(): Promise\ -**Required permissions**: none +Obtains the checked status of this component. **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | ----------------------------------- | -| Promise; | Promise used to return the scrollable status of the component.| +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the checked status of the component.| **Example** +```js +async function demo() { + let driver = UiDriver.create() + let checkBox = await driver.findComponent(BY.type('Checkbox')) + if(await checkBox.isChecked) { + console.info('This checkBox is checked') + } + else{ + console.info('This checkBox is not checked') + } +} ``` + +### UiComponent.isCheckable9+ + +isCheckable(): Promise\ + +Obtains the checked status of this component. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------------- | +| Promise\ | Promise used to return the checked status of the component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create() + let checkBox = await driver.findComponent(BY.type('Checkbox')) + if(await checkBox.isCheckable) { + console.info('This checkBox is checkable') + } + else{ + console.info('This checkBox is not checkable') + } +} +``` + +### UiComponent.isScrollable + +isScrollable(): Promise\ + +Obtains the scrollable status of this component. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the scrollable status of the component.| + +**Example** + +```js async function demo() { let driver = UiDriver.create() let scrollBar = await driver.findComponent(BY.scrollable(true)) @@ -596,23 +729,21 @@ async function demo() { ### UiComponent.isEnabled -isEnabled():Promise; +isEnabled(): Promise\ -Obtains the enable status of this component. - -**Required permissions**: none +Obtains the enabled status of this component. **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | ----------------------------- | -| Promise; | Promise used to return the enable status of the component.| +| Type | Description | +| -------------- | ------------------------------- | +| Promise\ | Promise used to return the enabled status of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -628,23 +759,21 @@ async function demo() { ### UiComponent.isFocused -isFocused():Promise; +isFocused(): Promise\ Obtains the focused status of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | --------------------------------- | -| Promise; | Promise used to return the focused status of the component.| +| Type | Description | +| -------------- | ----------------------------------- | +| Promise\ | Promise used to return the focused status of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -659,23 +788,21 @@ async function demo() { ### UiComponent.isSelected -isSelected():Promise; +isSelected(): Promise\ Obtains the selected status of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | ----------------------------------- | -| Promise; | Promise used to return the selected status of the component.| +| Type | Description | +| -------------- | -------------------- | +| Promise\ | Promise used to return the selected status of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -690,37 +817,51 @@ async function demo() { ### UiComponent.inputText -inputText(text: string):Promise; +inputText(text: string): Promise\ Enters text into this component (available for text boxes). -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------- | -| text | string | Yes | Text to be entered to the component.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| text | string | Yes | Text to enter.| **Example** +```js +async function demo() { + let driver = UiDriver.create() + let text = await driver.findComponent(BY.text('hello world')) + await text.inputText('123') +} ``` + +### UiComponent.clearText9+ + +clearText(): Promise\ + +Clears text in this component (available for text boxes). + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +```js async function demo() { let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - await button.inputText('next page') + let text = await driver.findComponent(BY.text('hello world')) + await text.clearText() } ``` ### UiComponent.scrollSearch -scrollSearch(by:By):Promise; - -Scrolls on this component to search for the target component (available for lists). +scrollSearch(by: By): Promise\ -**Required permissions**: none +Scrolls on this component to search for the target component (applicable to component that support scrolling, such as **\**). **System capability**: SystemCapability.Test.UiTest @@ -732,20 +873,81 @@ Scrolls on this component to search for the target component (available for list **Return value** -| Type | Description | -| --------------------- | ----------------------------------- | -| Promise; | Promise used to return the target component.| +| Type | Description | +| --------------------- | ------------------------------------- | +| Promise\ | Promise used to return the target component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() - let scrollBar = await driver.findComponent(BY.scrollable(true)) + let scrollBar = await driver.findComponent(BY.type('Scroll')) let button = await scrollBar.scrollSearch(BY.text('next page')) } ``` +### UiComponent.scrollToTop9+ + +scrollToTop(): Promise\ + +Scrolls to the top of this a component (applicable to component that support scrolling, such as **\**). + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +```js +async function demo() { + let driver = UiDriver.create() + let scrollBar = await driver.findComponent(BY.type('Scroll')) + await scrollBar.scrollToTop() +} +``` + +### UiComponent.scrollToBottom9+ + +scrollToBottom(): Promise\ + +Scrolls to the bottom of this a component (applicable to component that support scrolling, such as **\**). + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +```js +async function demo() { + let driver = UiDriver.create() + let scrollBar = await driver.findComponent(BY.type('Scroll')) + await scrollBar.scrollToBottom() +} +``` + +### UiComponent.dragTo9+ + +dragTo(target: UiComponent): Promise\ + +Drags this component to the target component. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------- | ---- | ---------- | +| target | UiComponent | Yes | Target component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + let text = await driver.findComponent(BY.text('hello world')) + await button.dragTo(text) + } +``` + ## UiDriver The **UiDriver** class is the main entry to the **uitest** test framework. It provides APIs for features such as component matching/search, key injection, coordinate clicking/sliding, and screenshot. @@ -753,23 +955,21 @@ All APIs provided by this class, except for **UiDriver.create()**, use a promise ### UiDriver.create -static create():UiDriver; +static create(): UiDriver Creates a **UiDriver** object and returns the object created. This API is a static API. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| ------- | ---------------------- | +| Type | Description | +| ------- | ------------------------ | | UiDrive | Returns the **UiDriver** object created.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() } @@ -777,23 +977,21 @@ async function demo() { ### UiDriver.delayMs -delayMs(duration:number):Promise; +delayMs(duration: number): Promise\ Delays this **UiDriver** object within the specified duration. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ---------- | +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------ | | duration | number | Yes | Duration of time.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.delayMs(1000) @@ -802,29 +1000,27 @@ async function demo() { ### UiDriver.findComponent -findComponent(by:By):Promise; - -Searches this **UiDriver** object for the target component that has the given attributes. +findComponent(by: By): Promise\ -**Required permissions**: none +Searches this **UiDriver** object for the target component that matches the given attributes. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------- | | by | By | Yes | Attributes of the target component.| **Return value** -| Type | Description | -| --------------------- | ------------------------------- | -| Promise; | Promise used to return the found component.| +| Type | Description | +| --------------------- | --------------------------------- | +| Promise\ | Promise used to return the found component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.text('next page')) @@ -833,54 +1029,80 @@ async function demo() { ### UiDriver.findComponents -findComponents(by:By):Promise>; +findComponents(by: By): Promise\> Searches this **UiDriver** object for all components that match the given attributes. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------- | | by | By | Yes | Attributes of the target component.| **Return value** -| Type | Description | -| ---------------------------- | ------------------------------------- | -| Promise>; | Promise used to return a list of found components.| +| Type | Description | +| ----------------------------- | --------------------------------------- | +| Promise\> | Promise used to return a list of found components.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let buttonList = await driver.findComponents(BY.text('next page')) } ``` +### UiDriver.waitForComponent9+ + +waitForComponent(by: By, time: number): Promise\ + +Searches this **UiDriver** object for the target component that matches the given attributes within the specified duration. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------- | +| by | By | Yes | Attributes of the target component. | +| time | number | Yes | Duration for searching for the target component, in ms.| + +**Return value** + +| Type | Description | +| --------------------- | --------------------------------- | +| Promise\ | Promise used to return the found component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.waitForComponent(BY.text('next page'),500) +} +``` + ### UiDriver.assertComponentExist -assertComponentExist(by:By):Promise; +assertComponentExist(by: By): Promise\ Asserts that a component that matches the given attributes exists on the current page. If the component does not exist, the API throws a JS exception, causing the current test case to fail. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------- | | by | By | Yes | Attributes of the target component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.assertComponentExist(BY.text('next page')) @@ -889,17 +1111,15 @@ async function demo() { ### UiDriver.pressBack -pressBack():Promise; +pressBack(): Promise\ Presses the Back button on this **UiDriver** object. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.pressBack() @@ -908,23 +1128,21 @@ async function demo() { ### UiDriver.triggerKey -triggerKey(keyCode:number):Promise; +triggerKey(keyCode: number): Promise\ Triggers the key of this **UiDriver** object that matches the given key code. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | --------- | +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------- | | keyCode | number | Yes | Key code.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.triggerKey(123) @@ -933,23 +1151,22 @@ async function demo() { ### UiDriver.click -click(x:number,y:number):Promise; +click(x: number, y: number): Promise\ Clicks a specific point of this **UiDriver** object based on the given coordinates. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------- | ---- | ------------------------------------------- | -| x,y | number,number | Yes | Coordinate information of a specific point in the (number,number) format.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| x | number | Yes | X coordinate of the target point.| +| y | number | Yes | Y coordinate of the target point.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.click(100,100) @@ -958,23 +1175,22 @@ async function demo() { ### UiDriver.doubleClick -doubleClick(x:number,y:number):Promise; +doubleClick(x: number, y: number): Promise\ Double-clicks a specific point of this **UiDriver** object based on the given coordinates. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------- | ---- | ------------------------------------------- | -| x,y | number,number | Yes | Coordinate information of a specific point in the (number,number) format.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| x | number | Yes | X coordinate of the target point.| +| y | number | Yes | Y coordinate of the target point.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.doubleClick(100,100) @@ -983,23 +1199,22 @@ async function demo() { ### UiDriver.longClick -longClick(x:number,y:number):Promise; +longClick(x: number, y: number): Promise\ Long-clicks a specific point of this **UiDriver** object based on the given coordinates. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------- | ---- | ------------------------------------------- | -| x,y | number,number | Yes | Coordinate information of a specific point in the (number,number) format.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| x | number | Yes | X coordinate of the target point.| +| y | number | Yes | Y coordinate of the target point.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.longClick(100,100) @@ -1008,51 +1223,96 @@ async function demo() { ### UiDriver.swipe -swipe(startx:number,starty:number,endx:number,endy:number):Promise; - -Swipes from the start point to the end point of this **UiDriver** object based on the given coordinates. +swipe(startx: number, starty: number, endx: number, endy: number): Promise\ -**Required permissions**: none +Swipes on this **UiDriver** object from the start point to the end point based on the given coordinates. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------- | ---- | ------------------------------------------- | -| startx,starty | number,number | Yes | Coordinate information of the start point in the (number,number) format.| -| endx,endy | number,number | Yes | Coordinate information of the end point in the (number,number) format.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| startx | number | Yes | X coordinate of the start point.| +| starty | number | Yes | Y coordinate of the start point.| +| endx | number | Yes | X coordinate of the end point.| +| endy | number | Yes | Y coordinate of the end point.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.swipe(100,100,200,200) } ``` +### UiDriver.drag9+ + +drag(startx: number, starty: number, endx: number, endy: number): Promise\ + +Drags this **UiDriver** object from the given start point to the given end point. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| startx | number | Yes | X coordinate of the start point.| +| starty | number | Yes | Y coordinate of the start point.| +| endx | number | Yes | X coordinate of the end point.| +| endy | number | Yes | Y coordinate of the end point.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create() + await driver.drag(100,100,200,200) +} +``` + ### UiDriver.screenCap -screenCap(savePath:string):Promise; +screenCap(savePath: string): Promise\ Captures the current screen of this **UiDriver** object and saves it as a PNG image to the given save path. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ------------ | +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | -------------- | | savePath | string | Yes | File save path.| +**Return value** + +| Type | Description | +| -------------- | -------------------------------------- | +| Promise\ | Promise used to return the operation result. The value **true** means that the operation is successful.| + **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.screenCap('/local/tmp/') } ``` + +## MatchPattern + +Enumerates the match patterns supported for component attributes. + +**System capability**: SystemCapability.Test.UiTest + +| Name | Value | Description | +| ----------- | ---- | -------------- | +| EQUALS | 0 | Equal to the given value. | +| CONTAINS | 1 | Containing the given value. | +| STARTS_WITH | 2 | Starting from the given value.| +| ENDS_WITH | 3 | Ending with the given value.| + +### diff --git a/en/application-dev/reference/apis/js-apis-update.md b/en/application-dev/reference/apis/js-apis-update.md index d84b4bdcd5acbe6169c8172961f935f254f5a7d2..251c1d59b610f4d01372186d0e40d0521cf62ca8 100644 --- a/en/application-dev/reference/apis/js-apis-update.md +++ b/en/application-dev/reference/apis/js-apis-update.md @@ -134,11 +134,11 @@ Obtains the new version information. This function uses an asynchronous callback **Example** ``` -update.getNewVersionInfo(info => { +updater.getNewVersionInfo(info => { console.log("getNewVersionInfo success " + info.status); - console.log(`info versionName = ` + info.result[0].versionName); - console.log(`info versionCode = ` + info.result[0].versionCode); - console.log(`info verifyInfo = ` + info.result[0].verifyInfo); + console.log(`info versionName = ` + info.checkResult[0].versionName); + console.log(`info versionCode = ` + info.checkResult[0].versionCode); + console.log(`info verifyInfo = ` + info.checkResult[0].verifyInfo); }); ``` @@ -160,9 +160,9 @@ Obtains the new version information. This function uses a promise to return the ``` updater.getNewVersionInfo().then(value => { - console.log(`info versionName = ` + value.result[0].versionName); - console.log(`info versionCode = ` + value.result[0].versionCode); - console.log(`info verifyInfo = ` + value.result[0].verifyInfo); + console.log(`info versionName = ` + value.checkResult[0].versionName); + console.log(`info versionCode = ` + value.checkResult[0].versionCode); + console.log(`info verifyInfo = ` + value.checkResult[0].verifyInfo); }).catch(err => { console.log("getNewVersionInfo promise error: " + err.code); }); @@ -185,11 +185,11 @@ Checks whether the current version is the latest. This function uses an asynchro **Example** ``` -update.checkNewVersion(info => { +updater.checkNewVersion(info => { console.log("checkNewVersion success " + info.status); - console.log(`info versionName = ` + info.result[0].versionName); - console.log(`info versionCode = ` + info.result[0].versionCode); - console.log(`info verifyInfo = ` + info.result[0].verifyInfo); + console.log(`info versionName = ` + info.checkResult[0].versionName); + console.log(`info versionCode = ` + info.checkResult[0].versionCode); + console.log(`info verifyInfo = ` + info.checkResult[0].verifyInfo); }); ``` @@ -210,10 +210,10 @@ Checks whether the current version is the latest. This function uses a promise t **Example** ``` -update.checkNewVersion().then(value => { - console.log(`info versionName = ` + value.result[0].versionName); - console.log(`info versionCode = ` + value.result[0].versionCode); - console.log(`info verifyInfo = ` + value.result[0].verifyInfo); +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); }).catch(err => { console.log("checkNewVersion promise error: " + err.code); }); @@ -237,13 +237,13 @@ Verifies whether the update package is valid. **Example** ``` -update.on("verifyProgress", callback => { +updater.on("verifyProgress", callback => { console.info('on verifyProgress ' + callback.percent); }); update.verifyUpdatePackage("XXX", "XXX"); ``` -### rebootAndCleanUserData +### rebootAndCleanUserData8+ rebootAndCleanUserData(): Promise\ @@ -260,14 +260,14 @@ Reboots the device and clears the user partition data. This function uses a prom **Example** ``` -update.rebootAndCleanUserData().then(result => { +updater.rebootAndCleanUserData().then(result => { console.log("rebootAndCleanUserData " + result); }).catch(err => { console.info("rebootAndCleanUserData promise error: " + err.code); }); ``` -### rebootAndCleanUserData +### rebootAndCleanUserData8+ rebootAndCleanUserData(callback: AsyncCallback\): void @@ -284,7 +284,7 @@ Reboots the device and clears the user partition data. This function uses a prom **Example** ``` -update.rebootAndCleanUserData(result => { +updater.rebootAndCleanUserData(result => { console.log("rebootAndCleanUserData ", result) }); ``` @@ -306,7 +306,7 @@ Installs the update package. This function uses a promise to return the result. **Example** ``` -update.applyNewVersion().then(result => { +updater.applyNewVersion().then(result => { console.log("appVewVersion ", result) }).catch(err => { console.info("applyNewVersion promise error: " + err.code); @@ -330,7 +330,7 @@ Installs the update package. This function uses a promise to return the result. **Example** ``` -update.applyNewVersion(result => { +updater.applyNewVersion(result => { console.log("applyNewVersion ", result) }); ``` @@ -399,7 +399,7 @@ let policy = { autoUpgradeInterval: [ 2, 3 ], autoUpgradeCondition: 2 } -update.setUpdatePolicy(policy, result => { +updater.setUpdatePolicy(policy, result => { console.log("setUpdatePolicy ", result) }); ``` @@ -434,7 +434,7 @@ let policy = { autoUpgradeInterval: [ 2, 3 ], autoUpgradeCondition: 2 } -update.setUpdatePolicy(policy).then(result => +updater.setUpdatePolicy(policy).then(result => console.log("setUpdatePolicy ", result) ).catch(err => { console.log("setUpdatePolicy promise error: " + err.code); @@ -458,7 +458,7 @@ Obtains the update policy. This function uses an asynchronous callback to return **Example** ``` -update.getUpdatePolicy(policy => { +updater.getUpdatePolicy(policy => { console.log("getUpdatePolicy success"); console.log(`policy autoDownload = ` + policy.autoDownload); console.log(`policy autoDownloadNet = ` + policy.autoDownloadNet); @@ -483,7 +483,7 @@ Obtains the update policy. This function uses a promise to return the result. **Example** ``` -update.getUpdatePolicy().then(value => { +updater.getUpdatePolicy().then(value => { console.log(`info autoDownload = ` + value.autoDownload); console.log(`info autoDownloadNet = ` + value.autoDownloadNet); console.log(`info mode = ` + value.mode); diff --git a/en/application-dev/reference/apis/js-apis-uri.md b/en/application-dev/reference/apis/js-apis-uri.md index 4952c227c32677d8bc1f13b3cd07d448ff0d21f0..a6c8823599cfee6dba5288e6555d6c618fd414c8 100644 --- a/en/application-dev/reference/apis/js-apis-uri.md +++ b/en/application-dev/reference/apis/js-apis-uri.md @@ -1,12 +1,13 @@ # URI String Parsing -> ![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. ## Modules to Import -``` +```js import uri from '@ohos.uri' ``` @@ -41,7 +42,7 @@ A constructor used to create a URI instance. | Name| Type.| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| url | string | Yes| Yes| Input object.| +| uri | string | Yes| Yes| Input object.| **Example** @@ -60,7 +61,7 @@ toString(): string **System capability**: SystemCapability.Utils.Lang -Obtains the query string applicable to this URL. +Obtains the query string applicable to this URI. **Return value** @@ -71,8 +72,8 @@ Obtains the query string applicable to this URL. **Example** ```js -const url = new uri.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -url.toString() +const uri = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +uri.toString() ``` diff --git a/en/application-dev/reference/apis/js-apis-uripermissionmanager.md b/en/application-dev/reference/apis/js-apis-uripermissionmanager.md index 9f5d4734ad55fbcbdb6692c40a0b71e0a67e0a62..6bbf0f941909786361f651546a3fab9fe129c69c 100644 --- a/en/application-dev/reference/apis/js-apis-uripermissionmanager.md +++ b/en/application-dev/reference/apis/js-apis-uripermissionmanager.md @@ -1,6 +1,7 @@ # uriPermissionManager -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md index 9f105f845950f1f206c326dcd94c4adf8b83c12c..fd826706700190a3d2f042a155cca1a2e1c96b81 100755 --- a/en/application-dev/reference/apis/js-apis-url.md +++ b/en/application-dev/reference/apis/js-apis-url.md @@ -30,11 +30,11 @@ Creates a **URLSearchParams** instance. **Example** ```js -var objectParams = new URLSearchParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]); -var objectParams1 = new URLSearchParams({"fod" : 1 , "bard" : 2}); -var objectParams2 = new URLSearchParams('?fod=1&bard=2'); -var urlObject = new URL('https://developer.mozilla.org/?fod=1&bard=2'); -var params = new URLSearchParams(urlObject.search); +var objectParams = new Url.URLSearchParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]); +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); ``` @@ -56,8 +56,8 @@ Appends a key-value pair into the query string. **Example** ```js -let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); -let paramsObject = new URLSearchParams(urlObject.search.slice(1)); +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); ``` @@ -79,8 +79,8 @@ Deletes key-value pairs of the specified key. **Example** ```js -let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); -let paramsobject = new URLSearchParams(urlObject.search.slice(1)); +let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let paramsobject = new Url.URLSearchParams(urlObject.search.slice(1)); paramsobject.delete('fod'); ``` @@ -108,8 +108,8 @@ Obtains all the key-value pairs based on the specified key. **Example** ```js -let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); -let paramsObject = new URLSearchParams(urlObject.search.slice(1)); +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"]. ``` @@ -132,7 +132,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th **Example** ```js -var searchParamsObject = new URLSearchParams("keyName1=valueName1&keyName2=valueName2"); +var searchParamsObject = new Url.URLSearchParams("keyName1=valueName1&keyName2=valueName2"); for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pairs console.log(pair[0]+ ', '+ pair[1]); } @@ -165,7 +165,7 @@ Traverses the key-value pairs in the **URLSearchParams** instance by using a cal **Example** ```js -const myURLObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); +const myURLObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); myURLObject.searchParams.forEach((value, name, searchParams) => { console.log(name, value, myURLObject.searchParams === searchParams); }); @@ -196,7 +196,7 @@ Obtains the value of the first key-value pair based on the specified key. **Example** ```js -var paramsOject = new URLSearchParams(document.location.search.substring(1)); +var paramsOject = new Url.URLSearchParams(document.location.search.substring(1)); 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 @@ -226,8 +226,8 @@ Checks whether a key has a value. **Example** ```js -let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); -let paramsObject = new URLSearchParams(urlObject.search.slice(1)); +let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1)); paramsObject.has('bard') === true; ``` @@ -250,8 +250,8 @@ Sets the value for a key. If key-value pairs matching the specified key exist, t **Example** ```js -let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); -let paramsObject = new URLSearchParams(urlObject.search.slice(1)); +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. ``` @@ -267,7 +267,7 @@ Sorts all key-value pairs contained in this object based on the Unicode code poi **Example** ```js -var searchParamsObject = new URLSearchParams("c=3&a=9&b=4&d=2"); // Create a test URLSearchParams object +var searchParamsObject = new Url.URLSearchParams("c=3&a=9&b=4&d=2"); // Create a test URLSearchParams object searchParamsObject.sort(); // Sort the key/value pairs console.log(searchParamsObject.toString()); // Display the sorted query string // Output a=9&b=2&c=3&d=4 ``` @@ -290,7 +290,7 @@ Obtains an ES6 iterator that contains the keys of all the key-value pairs. **Example** ```js -var searchParamsObject = new URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing +var searchParamsObject = new Url.URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing for (var key of searchParamsObject .keys()) { // Output key-value pairs console.log(key); } @@ -314,7 +314,7 @@ Obtains an ES6 iterator that contains the values of all the key-value pairs. **Example** ```js -var searchParams = new URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing +var searchParams = new Url.URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing for (var value of searchParams.values()) { console.log(value); } @@ -338,7 +338,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th **Example** ```js -const paramsObject = new URLSearchParams('fod=bay&edg=bap'); +const paramsObject = new Url.URLSearchParams('fod=bay&edg=bap'); for (const [name, value] of paramsObject) { console.log(name, value); } @@ -362,8 +362,8 @@ Obtains search parameters that are serialized as a string and, if necessary, per **Example** ```js -let url = new URL('https://developer.exampleUrl/?fod=1&bard=2'); -let params = new URLSearchParams(url.search.slice(1)); +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); console.log(params.toString()); ``` @@ -410,17 +410,17 @@ Creates a URL. ```js var mm = 'http://username:password@host:8080'; -var a = new URL("/", mm); // Output 'http://username:password@host:8080/'; -var b = new URL(mm); // Output 'http://username:password@host:8080/'; -new URL('path/path1', b); // Output 'http://username:password@host:8080/path/path1'; -var c = new URL('/path/path1', b); // Output 'http://username:password@host:8080/path/path1'; -new URL('/path/path1', c); // Output 'http://username:password@host:8080/path/path1'; -new URL('/path/path1', a); // Output 'http://username:password@host:8080/path/path1'; -new URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1 -new URL('/path/path1', ''); // Raises a TypeError exception as '' is not a valid URL -new URL('/path/path1'); // Raises a TypeError exception as '/path/path1' is not a valid URL -new URL('http://www.shanxi.com', ); // Output http://www.shanxi.com/ -new URL('http://www.shanxi.com', b); // Output http://www.shanxi.com/ +var a = new Url.URL("/", mm); // Output 'http://username:password@host:8080/'; +var b = new Url.URL(mm); // Output 'http://username:password@host:8080/'; +new Url.URL('path/path1', b); // Output 'http://username:password@host:8080/path/path1'; +var c = new Url.URL('/path/path1', b); // Output 'http://username:password@host:8080/path/path1'; +new Url.URL('/path/path1', c); // Output 'http://username:password@host:8080/path/path1'; +new Url.URL('/path/path1', a); // Output 'http://username:password@host:8080/path/path1'; +new Url.URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1 +new Url.URL('/path/path1', ''); // Raises a TypeError exception as '' is not a valid URL +new Url.URL('/path/path1'); // Raises a TypeError exception as '/path/path1' is not a valid URL +new Url.URL('http://www.shanxi.com', ); // Output http://www.shanxi.com/ +new Url.URL('http://www.shanxi.com', b); // Output http://www.shanxi.com/ ``` @@ -441,7 +441,7 @@ Converts the parsed URL into a string. **Example** ```js -const url = new URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); url.toString() ``` @@ -462,6 +462,6 @@ Converts the parsed URL into a JSON string. **Example** ```js -const url = new URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +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 06aee1c2fe533edae1e869152beefc1b8afb1984..63beaae8031c42ad274d2e151dad4c029f799761 100644 --- a/en/application-dev/reference/apis/js-apis-usb.md +++ b/en/application-dev/reference/apis/js-apis-usb.md @@ -158,7 +158,6 @@ Requests the temporary permission for the application to access the USB device. }); ``` - ## usb.claimInterface claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number @@ -243,14 +242,13 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi console.log(`setConfiguration = ${ret}`); ``` - ## usb.setInterface setInterface(pipe: USBDevicePipe, iface: USBInterface): number Sets a USB interface. -Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and interfaces, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter. +Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and interfaces, call [usb.requestRight](#usbrequestright) to request the device access permission, call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter, and call [usb.claimInterface](#usbclaiminterface) to claim a USB interface.. **System capability**: SystemCapability.USB.USBManager @@ -290,7 +288,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi - **Return value** | Type| Description| | -------- | -------- | - | Uint8Array | Raw descriptor data. | + | Uint8Array | Raw descriptor data. The value **undefined** indicates that the operation has failed. | - **Example** ```js @@ -316,7 +314,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi - **Return value** | Type| Description| | -------- | -------- | - | number | File descriptor of the USB device. | + | number | File descriptor of the USB device. The value **-1** indicates that the operation has failed. | - **Example** ```js @@ -360,7 +358,7 @@ bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, tim Performs bulk transfer. -Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and endpoints, call [usb.requestRight](#usbrequestright) to request the device access permission, call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter, and call [usb.claimInterface](#usbclaiminterface) to claim the USB interface. +Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and endpoints, call [usb.requestRight](#usbrequestright) to request the device access permission, call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter, and call [usb.claimInterface](#usbclaiminterface) to claim a USB interface. **System capability**: SystemCapability.USB.USBManager @@ -381,7 +379,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ```js // Call usb.getDevices to obtain a data set. Then, obtain a USB device and its access permission. // Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device. - // Call usb.claimInterface to claim the USB interface. After that, call usb.bulkTransfer to start bulk transfer. + // Call usb.claimInterface to claim a USB interface. After that, call usb.bulkTransfer to start bulk transfer. usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => { console.log(`bulkTransfer = ${JSON.stringify(ret)}`); }); diff --git a/en/application-dev/reference/apis/js-apis-useriam-userauth.md b/en/application-dev/reference/apis/js-apis-useriam-userauth.md index 39b0daf04ecbf60d2f4cefbeb4b60416c187ed68..56ac3823f29e6cee7efa13094d4becf5528fa854 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md @@ -50,7 +50,7 @@ export default { try { console.info("auth onResult result = " + result); console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == 'SUCCESS') { + if (result == userIAM_userAuth.ResultCode.SUCCESS) { // Add the logic to be executed when the authentication is successful. } else { // Add the logic to be executed when the authentication fails. @@ -97,7 +97,7 @@ export default { } }); let cancelCode = this.auth.cancel(contextId); - if (cancelCode == userIAM_userAuth.Result.SUCCESS) { + if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { console.info("cancel auth success"); } else { console.error("cancel auth fail"); @@ -110,7 +110,7 @@ export default { getAuthenticator(): Authenticator -> **NOTE**
+> **NOTE**
> This API is not longer maintained since API version 8. You are advised to use [constructor](#constructor8). Obtains an **Authenticator** object for user authentication. @@ -122,7 +122,7 @@ Obtains an **Authenticator** object for user authentication. **Return value** | Type | Description | | ----------------------------------------- | ------------ | -| [Authenticator](#authenticatordeprecated) | **Authenticator** object obtained. | +| [Authenticator](#authenticatordeprecated) | **Authenticator** object obtained.| **Example** ```js @@ -131,7 +131,7 @@ Obtains an **Authenticator** object for user authentication. ## Authenticator(deprecated) -> **NOTE**
+> **NOTE**
> This object is not longer maintained since API version 8. You are advised to use [UserAuth](#userauth8). Provides methods to manage an **Authenticator** object. @@ -141,7 +141,7 @@ Provides methods to manage an **Authenticator** object. execute(type: string, level: string, callback: AsyncCallback<number>): void -> **NOTE**
+> **NOTE**
> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8). Performs user authentication. This API uses asynchronous callback to return the result. @@ -154,15 +154,15 @@ Performs user authentication. This API uses asynchronous callback to return the | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version. | -| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication. | +| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| +| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| | callback | AsyncCallback<number> | No | Callback used to return the result. | Parameters returned in callback | Type | Description | | ------ | ------------------------------------------------------------ | -| number | Authentication result. For details, see [AuthenticationResult](#authenticationresultdeprecated). | +| number | Authentication result. For details, see [AuthenticationResult](#authenticationresultdeprecated).| **Example** ```js @@ -180,7 +180,7 @@ Performs user authentication. This API uses asynchronous callback to return the execute(type:string, level:string): Promise<number> -> **NOTE**
+> **NOTE**
> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8). Performs user authentication. This API uses a promise to return the result. @@ -192,13 +192,13 @@ Performs user authentication. This API uses a promise to return the result. **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version. | -| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication. | +| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| +| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| **Return value** | Type | Description | | --------------------- | ------------------------------------------------------------ | -| Promise<number> | Promise used to return the authentication result, which is a number. For details, see [AuthenticationResult](#authenticationresultdeprecated). | +| Promise<number> | Promise used to return the authentication result, which is a number. For details, see [AuthenticationResult](#authenticationresultdeprecated).| **Example** @@ -213,7 +213,7 @@ authenticator.execute("FACE_ONLY", "S2").then((code)=>{ ## AuthenticationResult(deprecated) -> **NOTE**
+> **NOTE**
> This parameter is not longer maintained since API version 8. You are advised to use [ResultCode](#resultcode8). Enumerates the authentication results. @@ -222,7 +222,7 @@ Enumerates the authentication results. | Name | Default Value| Description | | ------------------ | ------ | -------------------------- | -| NO_SUPPORT | -1 | The device does not support the current authentication mode. | +| NO_SUPPORT | -1 | The device does not support the current authentication mode.| | SUCCESS | 0 | The authentication is successful. | | COMPARE_FAILURE | 1 | The feature comparison failed. | | CANCELED | 2 | The authentication was canceled by the user. | @@ -230,7 +230,7 @@ Enumerates the authentication results. | CAMERA_FAIL | 4 | The camera failed to start. | | BUSY | 5 | The authentication service is not available. Try again later. | | INVALID_PARAMETERS | 6 | The authentication parameters are invalid. | -| LOCKED | 7 | The user account is locked because the number of authentication failures has reached the threshold. | +| LOCKED | 7 | The user account is locked because the number of authentication failures has reached the threshold.| | NOT_ENROLLED | 8 | No authentication credential is registered. | | GENERAL_ERROR | 100 | Other errors. | @@ -252,7 +252,7 @@ A constructor used to create an **authenticator** object. | Type | Description | | ---------------------- | -------------------- | -| [UserAuth](#userauth8) | **Authenticator** object obtained. | +| [UserAuth](#userauth8) | **Authenticator** object obtained.| **Example** @@ -276,7 +276,7 @@ Obtains the authentication executor version. | Type | Description | | ------ | ---------------------- | -| number | Authentication executor version obtained. | +| number | Authenticator version obtained.| **Example** @@ -302,14 +302,14 @@ Checks whether the authentication capability of the specified trust level is ava | Name | Type | Mandatory| Description | | -------------- | ---------------------------------- | ---- | -------------------------- | -| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported. | +| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| | authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. | **Return value** | Type | Description | | ------ | ------------------------------------------------------------ | -| number | Whether the authentication capability of the specified trust level is available. For details, see [ResultCode](#resultcode8). | +| number | Whether the authentication capability of the specified trust level is available. For details, see [ResultCode](#resultcode8).| **Example** @@ -342,7 +342,7 @@ Performs user authentication. This API uses a callback to return the result. | Name | Type | Mandatory| Description | | -------------- | ---------------------------------------- | ---- | ------------------------ | | challenge | Uint8Array | Yes | Challenge value, which can be null. | -| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported. | +| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| | authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level. | | callback | [IUserAuthCallback](#iuserauthcallback8) | Yes | Callback used to return the result. | @@ -350,7 +350,7 @@ Performs user authentication. This API uses a callback to return the result. | Type | Description | | ---------- | ------------------------------------------------------------ | -| Uint8Array | ContextId, which is used as the input parameter of [cancelAuth](#cancelauth8). | +| Uint8Array | ContextId, which is used as the input parameter of [cancelAuth](#cancelauth8).| **Example** @@ -389,13 +389,13 @@ Cancels an authentication. | Name | Type | Mandatory| Description | | --------- | ---------- | ---- | ------------------------------------------ | -| contextID | Uint8Array | Yes | Context ID, which is obtained using [auth](#auth8). | +| contextID | Uint8Array | Yes | Context ID, which is obtained using [auth](#auth8).| **Return value** | Type | Description | | ------ | ------------------------ | -| number | Whether the authentication is canceled. | +| number | Whether the authentication is canceled.| **Example** @@ -429,7 +429,7 @@ Obtains the authentication result. | Name | Type | Mandatory| Description | | --------- | -------------------------- | ---- | ------------------------------------------------------------ | | result | number | Yes | Authentication result obtained. For details, see [ResultCode](#resultcode8). | -| extraInfo | [AuthResult](#authresult8) | Yes | Extended information, which varies depending on the authentication result.
If the authentication is successful, the user authentication token will be returned in **extraInfo**.
If the authentication fails, the remaining number of authentication times will be returned in **extraInfo**.
If the authentication executor is locked, the freeze time will be returned in **extraInfo**. | +| extraInfo | [AuthResult](#authresult8) | Yes | Extended information, which varies depending on the authentication result.
If the authentication is successful, the user authentication token will be returned in **extraInfo**.
If the authentication fails, the remaining number of authentication times will be returned in **extraInfo**.
If the authentication executor is locked, the freeze time will be returned in **extraInfo**.| **Example** @@ -443,7 +443,7 @@ Obtains the authentication result. try { console.info("auth onResult result = " + result); console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == SUCCESS) { + if (result == userIAM_userAuth.ResultCode.SUCCESS) { // Add the logic to be executed when the authentication is successful. } else { // Add the logic to be executed when the authentication fails. @@ -478,7 +478,7 @@ Obtains the tip code information during authentication. This function is optiona | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------------------------ | | module | number | Yes | Type of the authentication executor. | -| acquire | number | Yes | Interaction information of the authentication executor during the authentication process. | +| acquire | number | Yes | Interaction information of the authentication executor during the authentication process.| | extraInfo | any | Yes | Reserved field. | **Example** @@ -492,7 +492,7 @@ Obtains the tip code information during authentication. This function is optiona try { console.info("auth onResult result = " + result); console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == SUCCESS) { + if (result == userIAM_userAuth.ResultCode.SUCCESS) { // Add the logic to be executed when the authentication is successful. } else { // Add the logic to be executed when the authentication fails. @@ -523,8 +523,8 @@ Represents the authentication result object. | Name | Type | Mandatory| Description | | ------------ | ---------- | ---- | -------------------- | | token | Uint8Array | No | Identity authentication token. | -| remainTimes | number | No | Number of remaining authentication operations. | -| freezingTime | number | No | Time for which the authentication operation is frozen. | +| remainTimes | number | No | Number of remaining authentication operations.| +| freezingTime | number | No | Time for which the authentication operation is frozen.| ## ResultCode8+ @@ -544,7 +544,7 @@ Enumerates the operation results. | BUSY | 7 | Indicates the busy state. | | INVALID_PARAMETERS | 8 | Invalid parameters are detected. | | LOCKED | 9 | The authentication executor is locked. | -| NOT_ENROLLED | 10 | The user has not entered the authentication information. | +| NOT_ENROLLED | 10 | The user has not entered the authentication information.| ## FaceTips8+ @@ -563,7 +563,7 @@ Enumerates the tip codes used during the facial authentication process. | FACE_AUTH_TIP_TOO_LOW | 6 | Only the lower part of the face is captured because the device is angled too low. | | FACE_AUTH_TIP_TOO_RIGHT | 7 | Only the right part of the face is captured because the device is deviated to the right. | | FACE_AUTH_TIP_TOO_LEFT | 8 | Only the left part of the face is captured because the device is deviated to the left. | -| FACE_AUTH_TIP_TOO_MUCH_MOTION | 9 | The face moves too fast during facial information collection. | +| FACE_AUTH_TIP_TOO_MUCH_MOTION | 9 | The face moves too fast during facial information collection.| | FACE_AUTH_TIP_POOR_GAZE | 10 | The face is not facing the camera. | | FACE_AUTH_TIP_NOT_DETECTED | 11 | No face is detected. | @@ -577,7 +577,7 @@ Enumerates the tip codes used during the fingerprint authentication process. | Name | Default Value| Description | | --------------------------------- | ------ | -------------------------------------------------- | | FINGERPRINT_AUTH_TIP_GOOD | 0 | The obtained fingerprint image is in good condition. | -| FINGERPRINT_AUTH_TIP_DIRTY | 1 | Large fingerprint image noise is detected due to suspicious or detected dirt on the sensor. | +| FINGERPRINT_AUTH_TIP_DIRTY | 1 | Large fingerprint image noise is detected due to suspicious or detected dirt on the sensor.| | FINGERPRINT_AUTH_TIP_INSUFFICIENT | 2 | The noise of the fingerprint image is too large to be processed. | | FINGERPRINT_AUTH_TIP_PARTIAL | 3 | Incomplete fingerprint image is detected. | | FINGERPRINT_AUTH_TIP_TOO_FAST | 4 | The fingerprint image is incomplete due to fast movement. | @@ -592,8 +592,8 @@ Enumerates the identity authentication types. | Name | Default Value| Description | | ----------- | ------ | ---------- | -| FACE | 2 | Facial authentication. | -| FINGERPRINT | 4 | Fingerprint authentication. | +| FACE | 2 | Facial authentication.| +| FINGERPRINT | 4 | Fingerprint authentication.| ## AuthTrustLevel8+ @@ -603,7 +603,7 @@ Enumerates the trust levels of the authentication result. | Name| Default Value| Description | | ---- | ------ | ------------------------- | -| ATL1 | 10000 | Trust level 1. | -| ATL2 | 20000 | Trust level 2. | -| ATL3 | 30000 | Trust level 3. | -| ATL4 | 40000 | Trust level 4. | +| ATL1 | 10000 | Trust level 1.| +| ATL2 | 20000 | Trust level 2.| +| ATL3 | 30000 | Trust level 3.| +| ATL4 | 40000 | Trust level 4.| diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 0ee9fb84705d1c23d9c453e75dd47689bc66d1d3..f427cfe5749110480fd4d7400fc3e3cb1de2c6e7 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -208,9 +208,6 @@ Decodes the input content. result[4] = 0x62; result[5] = 0x63; console.log("input num:"); - for(var j= 0; j < 6; j++) { - console.log(result[j]); - } var retStr = textDecoder.decode( result , {stream: false}); console.log("retStr = " + retStr); ``` @@ -262,6 +259,7 @@ Encodes the input content. **Example** ```js var textEncoder = new util.TextEncoder(); + var buffer = new ArrayBuffer(20); var result = new Uint8Array(buffer); result = textEncoder.encode("\uD800¥¥"); ``` diff --git a/en/application-dev/reference/apis/js-apis-vector.md b/en/application-dev/reference/apis/js-apis-vector.md index 004ff8a1c46f14e2bb7916153de47cb7e25e5314..9288f871d45e7a08a542221ddf561e6a4e4fe81b 100644 --- a/en/application-dev/reference/apis/js-apis-vector.md +++ b/en/application-dev/reference/apis/js-apis-vector.md @@ -1,28 +1,31 @@ # Linear Container Vector -> **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. +**Vector** is a linear data structure that is implemented based on arrays. When the memory of a vector is used up, a larger contiguous memory area is automatically allocated, all the elements are copied to the new memory area, and the current memory area is reclaimed. **Vector** can be used to efficiently access elements. + +Both **Vector** and **[ArrayList](js-apis-arraylist.md)** are implemented based on arrays, but **Vector** provides more interfaces for operating the arrays. Both of them can dynamically adjust the capacity. **Vector** doubles the capacity each time, whereas **ArrayList** increases the capacity by 50%. + +**Recommended use case**: Use **Vector** when the data volume is large. ## Modules to Import ```ts -import Vector from '@ohos.util.Vector' +import Vector from '@ohos.util.Vector'; ``` -## System Capability - -SystemCapability.Utils.Lang - ## Vector - ### Attributes - | Name | Type | Readable | Writable | Description | - | -------- | -------- | -------- | -------- | -------- | - | length | number | Yes | No | Number of entries in a vector (called container later). | +**System capability**: SystemCapability.Utils.Lang + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| length | number | Yes| No| Number of elements in a vector (called container later).| ### constructor @@ -31,6 +34,8 @@ constructor() A constructor used to create a **Vector** instance. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -42,19 +47,21 @@ let vector = new Vector(); add(element: T): boolean -Adds an entry at the end of this container. +Adds an element at the end of this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | element | T | Yes | Entry to add. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| element | T | Yes| Target element.| **Return value** - | Type | Description | - | -------- | -------- | - | boolean | Returns **true** if the entry is added successfully; returns **false** otherwise. | +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the element is added successfully; returns **false** otherwise.| **Example** @@ -72,14 +79,16 @@ let result3 = vector.add(c); insert(element: T, index: number): void -Inserts an entry at the specified position in this container. +Inserts an element at the specified position in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | element | T | Yes | Entry to insert. | - | index | number | Yes | Index of the position where the entry is to be inserted. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| element | T | Yes| Target element.| +| index | number | Yes| Index of the position where the element is to be inserted.| **Example** @@ -94,19 +103,21 @@ vector.insert(true, 2); has(element: T): boolean -Checks whether this container has the specified entry. +Checks whether this container has the specified element. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | element | T | Yes | Entry to check. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| element | T | Yes| Target element.| **Return value** - | Type | Description | - | -------- | -------- | - | boolean | Returns **true** if the entry is contained; returns **false** otherwise. | +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the element is contained; returns **false** otherwise.| **Example** @@ -115,25 +126,27 @@ let vector = new Vector(); let result = vector.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); vector.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result1 = vector.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); -``` +``` ### getIndexOf getIndexOf(element: T): number -Obtains the index of the first occurrence of the specified entry in this container. +Obtains the index of the first occurrence of the specified element in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | element | T | Yes | Entry to obtain. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| element | T | Yes| Target element.| **Return value** - | Type | Description | - | -------- | -------- | - | number | Returns the position index if obtained; returns **-1** if the specified entry is not found. | +| Type| Description| +| -------- | -------- | +| number | Returns the position index if obtained; returns **-1** otherwise.| **Example** @@ -153,19 +166,21 @@ let result = vector.getIndexOf(2); getLastIndexOf(element: T): number -Obtains the index of the last occurrence of the specified entry in this container. +Obtains the index of the last occurrence of the specified element in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | element | T | Yes | Entry to obtain. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| element | T | Yes| Target element.| **Return value** - | Type | Description | - | -------- | -------- | - | number | Returns the position index if obtained; returns **-1** if the specified entry is not found. | +| Type| Description| +| -------- | -------- | +| number | Returns the position index if obtained; returns **-1** otherwise.| **Example** @@ -185,19 +200,21 @@ let result = vector.getLastIndexOf(2); removeByIndex(index: number): T -Removes an entry at the specified position from this container. +Removes an element at the specified position from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | index | number | Yes | Position index of the entry to remove. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| index | number | Yes| Position index of the target element.| **Return value** - | Type | Description | - | -------- | -------- | - | T | Entry removed. | +| Type| Description| +| -------- | -------- | +| T | Element removed.| **Example** @@ -215,19 +232,21 @@ let result = vector.removeByIndex(2); remove(element: T): boolean -Removes the first occurrence of the specified entry from this container. +Removes the first occurrence of the specified element from this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | element | T | Yes | Entry to remove. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| element | T | Yes| Target element.| **Return value** - | Type | Description | - | -------- | -------- | - | boolean | Returns **true** if the entry is removed successfully; returns **false** otherwise. | +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the element is removed successfully; returns **false** otherwise.| **Return value** @@ -244,14 +263,16 @@ let result = vector.remove(2); removeByRange(fromIndex: number, toIndex: number): void -Removes from this container all of the entries within a range, including the entry at the start position but not that at the end position. +Removes from this container all of the elements within a range, including the element at the start position but not that at the end position. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | fromIndex | number | Yes | Index of the start position. | - | toIndex | number | Yes | Index of the end position. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| fromIndex | number | Yes| Index of the start position.| +| toIndex | number | Yes| Index of the end position.| **Example** @@ -271,22 +292,24 @@ vector.removeByRange(2,6); replaceAllElements(callbackfn: (value: T, index?: number, vector?: Vector<T>) => T, thisArg?: Object): void -Replaces all entries in this container with new entries, and returns the new ones. +Replaces all elements in this container with new elements, and returns the new ones. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | callbackfn | function | Yes | Callback invoked for replacement. | - | thisArg | Object | No | Value to use when the callback is invoked. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callbackfn | function | Yes| Callback invoked for replacement.| +| thisArg | Object | No| Value to use when the callback is invoked.| callbackfn - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | value | T | Yes | Value of the entry that is currently traversed. | - | index | number | No | Position index of the entry that is currently traversed. | - | vector | Vector<T> | No | Instance that invokes the **replaceAllElements** API. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | T | Yes| Value of the element that is currently traversed.| +| index | number | No| Position index of the element that is currently traversed.| +| vector | Vector<T> | No| Instance that invokes the **replaceAllElements** API.| **Example** @@ -309,22 +332,24 @@ vector.replaceAllElements((value, index) => { forEach(callbackfn: (value: T, index?: number, vector?: Vector<T>) => void, thisArg?: Object): void -Uses a callback to traverse the entries in this container and obtain their position indexes. +Uses a callback to traverse the elements in this container and obtain their position indexes. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | callbackfn | function | Yes | Callback invoked for replacement. | - | thisArg | Object | No | Value to use when the callback is invoked. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callbackfn | function | Yes| Callback invoked for replacement.| +| thisArg | Object | No| Value to use when the callback is invoked.| callbackfn - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | value | T | Yes | Value of the entry that is currently traversed. | - | index | number | No | Position index of the entry that is currently traversed. | - | vector | Vector<T> | No | Instance that invokes the **forEach** API. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | T | Yes| Value of the element that is currently traversed.| +| index | number | No| Position index of the element that is currently traversed.| +| vector | Vector<T> | No| Instance that invokes the **forEach** API.| **Example** @@ -335,7 +360,7 @@ vector.add(4); vector.add(5); vector.add(4); vector.forEach((value, index) => { - console.log(value, index) + console.log("value:" + value, index) }); ``` @@ -344,20 +369,22 @@ vector.forEach((value, index) => { sort(comparator?: (firstValue: T, secondValue: T) => number): void -Sorts entries in this container. +Sorts elements in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | comparator | function | No | Callback invoked for sorting. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| comparator | function | No| Callback invoked for sorting.| comparator - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | firstValue | T | Yes | Previous entry. | - | secondValue | T | Yes | Next entry. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| firstValue | T | Yes| Previous element.| +| secondValue | T | Yes| Next element.| **Example** @@ -367,8 +394,8 @@ vector.add(2); vector.add(4); vector.add(5); vector.add(4); -vector.sort(a, (b => a - b)); -vector.sort(a, (b => b - a)); +vector.sort((a, b) => a - b); +vector.sort((a, b) => b - a); vector.sort(); ``` @@ -376,20 +403,22 @@ vector.sort(); subVector(fromIndex: number, toIndex: number): Vector<T> -Obtains entries within a range in this container, including the entry at the start position but not that at the end position, and returns these entries as a new **Vector** instance. +Obtains elements within a range in this container, including the element at the start position but not that at the end position, and returns these elements as a new **Vector** instance. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | fromIndex | number | Yes | Index of the start position. | - | toIndex | number | Yes | Index of the end position. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| fromIndex | number | Yes| Index of the start position.| +| toIndex | number | Yes| Index of the end position.| **Return value** - | Type | Description | - | -------- | -------- | - | Vector<T> | New **Vector** instance obtained. | +| Type| Description| +| -------- | -------- | +| Vector<T> | New **Vector** instance obtained.| **Return value** @@ -409,7 +438,9 @@ let result2 = vector.subVector(2,6); clear(): void -Clears all entries in this container and sets its length to **0**. +Clears all elements in this container and sets its length to **0**. + +**System capability**: SystemCapability.Utils.Lang **Return value** @@ -428,11 +459,13 @@ clone(): Vector<T> Clones this container and returns a copy. The modification to the copy does not affect the original instance. +**System capability**: SystemCapability.Utils.Lang + **Return value** - | Type | Description | - | -------- | -------- | - | Vector<T> | New **Vector** instance obtained. | +| Type| Description| +| -------- | -------- | +| Vector<T> | New **Vector** instance obtained.| **Example** @@ -451,11 +484,13 @@ getCapacity(): number Obtains the capacity of this container. +**System capability**: SystemCapability.Utils.Lang + **Return value** - | Type | Description | - | -------- | -------- | - | number | Capacity obtained. | +| Type| Description| +| -------- | -------- | +| number | Capacity obtained.| **Example** @@ -474,11 +509,13 @@ convertToArray(): Array<T> Converts this container into an array. +**System capability**: SystemCapability.Utils.Lang + **Return value** - | Type | Description | - | -------- | -------- | - | Array<T> | Array obtained. | +| Type| Description| +| -------- | -------- | +| Array<T> | Array obtained.| **Example** @@ -495,13 +532,15 @@ let result = vector.convertToArray(); isEmpty(): boolean -Checks whether this container is empty (contains no entries). +Checks whether this container is empty (contains no elements). + +**System capability**: SystemCapability.Utils.Lang **Return value** - | Type | Description | - | -------- | -------- | - | boolean | Returns **true** if the container is empty; returns **false** otherwise. | +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the container is empty; returns **false** otherwise.| **Example** @@ -520,11 +559,13 @@ increaseCapacityTo(newCapacity: number): void Increases the capacity of this container. +**System capability**: SystemCapability.Utils.Lang + **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | newCapacity | number | Yes | New capacity. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| newCapacity | number | Yes| New capacity.| **Example** @@ -544,6 +585,8 @@ trimToCurrentLength(): void Trims the capacity of this container into its current length. +**System capability**: SystemCapability.Utils.Lang + **Example** ```ts @@ -559,13 +602,15 @@ vector.trimToCurrentLength(); toString(): string -Uses commas (,) to concatenate entries in this container into a string. +Uses commas (,) to concatenate elements in this container into a string. + +**System capability**: SystemCapability.Utils.Lang **Return value** - | Type | Description | - | -------- | -------- | - | string | String obtained. | +| Type| Description| +| -------- | -------- | +| string | String obtained.| **Example** @@ -582,13 +627,15 @@ let result = vector.toSting(); copyToArray(array: Array<T>): void -Copies entries in this container into an array to overwrite elements of the same position indexes. +Copies elements in this container into an array to overwrite elements of the same position indexes. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | array | Array<T> | Yes | Array to which the entries in the container will be copied. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| array | Array<T> | Yes| Array to which the elements in the container will be copied.| **Example** @@ -606,13 +653,15 @@ let result = vector.copyToArray(array); getFirstElement(): T -Obtains the first entry in this container. +Obtains the first element in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** - | Type | Description | - | -------- | -------- | - | T | The first entry obtained. | +| Type| Description| +| -------- | -------- | +| T | The first element obtained.| **Example** @@ -629,13 +678,15 @@ let result = vector.getFirstElement(); getLastElement(): T -Obtains the last entry in this container. +Obtains the last element in this container. + +**System capability**: SystemCapability.Utils.Lang **Return value** - | Type | Description | - | -------- | -------- | - | T | The last entry obtained. | +| Type| Description| +| -------- | -------- | +| T | The last element obtained.| **Example** @@ -652,20 +703,22 @@ let result = vector.getLastElement(); getLastIndexFrom(element: T, index: number): number -Searches for an entry backward from the specified position index and returns the position index of the entry. +Searches for an element backward from the specified position index and returns the position index of the element. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | element | T | Yes | Entry to query. | - | index | number | Yes | Position index where the search starts. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| element | T | Yes| Target element.| +| index | number | Yes| Position index where the search starts.| **Return value** - | Type | Description | - | -------- | -------- | - | number | Returns the position index if obtained; returns **-1** if the entry is not found. | +| Type| Description| +| -------- | -------- | +| number | Returns the position index if obtained; returns **-1** otherwise.| **Example** @@ -683,20 +736,22 @@ let result = vector.getLastIndexFrom(4,3); getIndexFrom(element: T, index: number): number -Searches for an entry forward from the specified position index and returns the position index of the entry. +Searches for an element forward from the specified position index and returns the position index of the element. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | element | T | Yes | Entry to query. | - | index | number | Yes | Position index where the search starts. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| element | T | Yes| Target element.| +| index | number | Yes| Position index where the search starts.| **Return value** - | Type | Description | - | -------- | -------- | - | number | Returns the position index if obtained; returns **-1** if the entry is not found. | +| Type| Description| +| -------- | -------- | +| number | Returns the position index if obtained; returns **-1** otherwise.| **Example** @@ -716,11 +771,13 @@ setLength(newSize: number): void Sets a new length for this container. +**System capability**: SystemCapability.Utils.Lang + **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | newSize | number | Yes | New length to set. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| newSize | number | Yes| New length to set.| **Example** @@ -738,19 +795,21 @@ vector.setLength(2); get(index: number): T -Obtains an entry at the specified position in this container. +Obtains an element at the specified position in this container. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | index | number | Yes | Position index of the entry to obtain. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| index | number | Yes| Position index of the target element.| **Return value** - | Type | Description | - | -------- | -------- | - | T | Entry obtained. | +| Type| Description| +| -------- | -------- | +| T | Element obtained.| **Example** @@ -766,20 +825,22 @@ Obtains an entry at the specified position in this container. set(index: number, element: T): T -Replaces an entry at the specified position in this container with a given entry. +Replaces an element at the specified position in this container with a given element. + +**System capability**: SystemCapability.Utils.Lang **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | index | number | Yes | Position index of the entry to replace. | - | element | T | Yes | Entry to be used for replacement. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| index | number | Yes| Position index of the target element.| +| element | T | Yes| Element to be used for replacement.| **Return value** - | Type | Description | - | -------- | -------- | - | T | New entry. | +| Type| Description| +| -------- | -------- | +| T | New element.| **Example** @@ -796,13 +857,15 @@ Replaces an entry at the specified position in this container with a given entry [Symbol.iterator]\(): IterableIterator<T> - Obtains an iterator. Each item of the iterator is a JavaScript object. +**System capability**: SystemCapability.Utils.Lang + **Return value** - | Type | Description | - | -------- | -------- | - | IterableIterator<T> | Iterator obtained. | + +| Type| Description| +| -------- | -------- | +| IterableIterator<T> | Iterator obtained.| **Example** @@ -815,14 +878,14 @@ vector.add(4); // Method 1: for (let item of vector) { - console.log(item); + console.log("value:" + item); } // Method 2: let iter = vector[Symbol.iterator](); let temp = iter.next().value; while(temp != undefined) { - console.log(temp); + console.log("value:" + temp); temp = iter.next().value; } ``` diff --git a/en/application-dev/reference/apis/js-apis-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md index 6ea1af902df9dd714aa0e3476c3419011a21f2d2..ac1b476b50dec7bc578cea40902cd863ce0999f9 100644 --- a/en/application-dev/reference/apis/js-apis-vibrator.md +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -1,12 +1,15 @@ + + # Vibrator -> **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. ## Modules to Import -``` +```js import vibrator from '@ohos.vibrator'; ``` @@ -23,18 +26,18 @@ Triggers vibration with a specific duration. This API uses a promise to return t **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ------ | ---- | ------------ | - | duration | number | Yes | Vibration duration. | +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------ | +| duration | number | Yes | Vibration duration.| **Return value** - | Type | Description | - | ------------------- | ----------- | - | Promise<void> | Promise used to indicate whether the vibration is triggered successfully. | +| Type | Description | +| ------------------- | ----------- | +| Promise<void> | Promise used to indicate whether the vibration is triggered successfully.| **Example** - ``` + ```js vibrator.vibrate(1000).then(()=>{ console.log("Promise returned to indicate a successful vibration."); }, (error)=>{ @@ -54,13 +57,13 @@ Triggers vibration with a specific duration. This API uses an asynchronous callb **System capability**: SystemCapability.Sensors.MiscDevice **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ------------------------- | ---- | ----------------------- | - | duration | number | Yes | Vibration duration. | - | callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is triggered successfully. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------------------- | +| duration | number | Yes | Vibration duration. | +| callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is triggered successfully.| **Example** - ``` + ```js vibrator.vibrate(1000,function(error){ if(error){ console.log("error.code"+error.code+"error.message"+error.message); @@ -82,17 +85,17 @@ Triggers vibration with a specific effect. This API uses a promise to return the **System capability**: SystemCapability.Sensors.MiscDevice **Parameters** - | Name | Type | Mandatory | Description | - | -------- | --------------------- | ---- | ------------- | - | effectId | [EffectId](#effectid) | Yes | String that indicates the vibration effect. | +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | ------------- | +| effectId | [EffectId](#effectid) | Yes | Vibration effect. | **Return value** - | Type | Description | - | ------------------- | ----------- | - | Promise<void> | Promise used to indicate whether the vibration is triggered successfully. | +| Type | Description | +| ------------------- | ----------- | +| Promise<void> | Promise used to indicate whether the vibration is triggered successfully.| **Example** - ``` + ```js vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(()=>{ console.log("Promise returned to indicate a successful vibration."); }, (error)=>{ @@ -112,13 +115,13 @@ Triggers vibration with a specific effect. This API uses an asynchronous callbac **System capability**: SystemCapability.Sensors.MiscDevice **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ------------------------- | ---- | ----------------------- | - | effectId | [EffectId](#effectid) | Yes | String that indicates the vibration effect. | - | callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is triggered successfully. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------------------- | +| effectId | [EffectId](#effectid) | Yes | Vibration effect. | +| callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is triggered successfully.| **Example** - ``` + ```js vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function(error){ if(error){ console.log("error.code"+error.code+"error.message"+error.message); @@ -140,17 +143,17 @@ Stops the vibration based on the specified **stopMode**. This API uses a promise **System capability**: SystemCapability.Sensors.MiscDevice **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ------------------------------------- | ---- | --------------- | - | stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Vibration mode to stop. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------- | ---- | --------------- | +| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Vibration mode to stop.| **Return value** - | Type | Description | - | ------------------- | ----------- | - | Promise<void> | Promise used to indicate whether the vibration is stopped successfully. | +| Type | Description | +| ------------------- | ----------- | +| Promise<void> | Promise used to indicate whether the vibration is stopped successfully.| **Example** - ``` + ```js vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ console.log("Promise returned to indicate a successful vibration."); }, (error)=>{ @@ -170,13 +173,13 @@ Stops the vibration based on the specified **stopMode**. This API uses an asynch **System capability**: SystemCapability.Sensors.MiscDevice **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ------------------------------------- | ---- | ----------------------- | - | stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Vibration mode to stop. | - | callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is stopped successfully. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------- | ---- | ----------------------- | +| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Vibration mode to stop. | +| callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is stopped successfully.| **Example** - ``` + ```js vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){ if(error){ console.log("error.code"+error.code+"error.message"+error.message); @@ -193,9 +196,9 @@ Describes the vibration effect. **System capability**: SystemCapability.Sensors.MiscDevice - | Name | Default Value | Description | - | ------------------ | -------------------- | --------------------------------------------------------------- | - | EFFECT_CLOCK_TIMER | "haptic.clock.timer" | Vibration effect of the vibrator when a user adjusts the timer. | +| Name | Default Value | Description | +| ------------------ | -------------------- | --------------- | +| EFFECT_CLOCK_TIMER | "haptic.clock.timer" | Vibration effect of the vibrator when a user adjusts the timer.| ## VibratorStopMode @@ -204,7 +207,7 @@ Describes the vibration mode to stop. **System capability**: SystemCapability.Sensors.MiscDevice - | Name | Default Value | Description | - | ------------------------- | -------- | ---------------------------------------- | - | VIBRATOR_STOP_MODE_TIME | "time" | The vibration to stop is in **duration** mode. This vibration is triggered with the parameter **duration** of the **number** type. | - | VIBRATOR_STOP_MODE_PRESET | "preset" | The vibration to stop is in **EffectId** mode. This vibration is triggered with the parameter **effectId** of the **EffectId** type. | +| Name | Default Value | Description | +| ------------------------- | -------- | ---------------------------------------- | +| VIBRATOR_STOP_MODE_TIME | "time" | The vibration to stop is in **duration** mode. This vibration is triggered with the parameter **duration** of the **number** type.| +| VIBRATOR_STOP_MODE_PRESET | "preset" | The vibration to stop is in **EffectId** mode. This vibration is triggered with the parameter **effectId** of the **EffectId** type.| diff --git a/en/application-dev/reference/apis/js-apis-volumemanager.md b/en/application-dev/reference/apis/js-apis-volumemanager.md index 16ca7a6a06903f063a22590981cc3ed3b3ed8cd1..39333510193d27d613ba48896e58f2d1dd3434f5 100644 --- a/en/application-dev/reference/apis/js-apis-volumemanager.md +++ b/en/application-dev/reference/apis/js-apis-volumemanager.md @@ -1,9 +1,12 @@ # Volume Management -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE**
> > - The initial APIs of this module are supported since API version 9. -> - API version 9 is a canary release for trial use. The APIs of this version may be unstable. +> - API version 9 is a canary version for trial use. The APIs of this version may be unstable. +> - The APIs of this module are system APIs and cannot be called by third-party applications. + +The APIs of this module can be used to perform volume and disk management, including obtaining volume information, mounting and unmounting volumes, partitioning disks, and formatting volumes. ## Modules to Import @@ -15,7 +18,7 @@ import volumemanager from "@ohos.volumeManager"; getAllVolumes(): Promise<Array<Volume>> -Asynchronously obtains information about all available volumes. This method uses a promise to return the result. +Asynchronously obtains information about all available volumes. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.StorageService.Volume @@ -37,7 +40,7 @@ Asynchronously obtains information about all available volumes. This method uses getAllVolumes(callback: AsyncCallback<Array<Volume>>): void -Asynchronously obtains information about all available volumes. This method uses a callback to return the result. +Asynchronously obtains information about all available volumes. This API uses a callback to return the result. **System capability**: SystemCapability.FileManagement.StorageService.Volume @@ -61,7 +64,7 @@ Asynchronously obtains information about all available volumes. This method uses mount(volumeId: string): Promise<boolean> -Asynchronously mounts a volume. This method uses a promise to return the result. +Asynchronously mounts a volume. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.StorageService.Volume @@ -90,7 +93,7 @@ Asynchronously mounts a volume. This method uses a promise to return the result. mount(volumeId: string, callback:AsyncCallback<boolean>):void -Asynchronously obtains the available space of the specified volume. This method uses a callback to return the result. +Asynchronously obtains the available space of the specified volume. This API uses a callback to return the result. **System capability**: SystemCapability.FileManagement.StorageService.Volume @@ -114,7 +117,7 @@ Asynchronously obtains the available space of the specified volume. This method unmount(volumeId: string): Promise<boolean> -Asynchronously unmounts a volume. This method uses a promise to return the result. +Asynchronously unmounts a volume. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.StorageService.Volume @@ -143,7 +146,7 @@ Asynchronously unmounts a volume. This method uses a promise to return the resul unmount(volumeId: string, callback:AsyncCallback<boolean>):void -Asynchronously unmounts a volume. This method uses a callback to return the result. +Asynchronously unmounts a volume. This API uses a callback to return the result. **System capability**: SystemCapability.FileManagement.StorageService.Volume diff --git a/en/application-dev/reference/apis/js-apis-wallpaper.md b/en/application-dev/reference/apis/js-apis-wallpaper.md index 726134af57d86fcb611dd5a03c898d3e656bd272..75dda908af3e32140bf7c94b92ff73117be0ad7e 100644 --- a/en/application-dev/reference/apis/js-apis-wallpaper.md +++ b/en/application-dev/reference/apis/js-apis-wallpaper.md @@ -1,8 +1,7 @@ # Wallpaper -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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 @@ -29,18 +28,18 @@ Defines the wallpaper type. getColors(wallpaperType: WallpaperType, callback: AsyncCallback<Array<RgbaColor>>): void -Obtains the main color information of the wallpaper of a specified type. +Obtains the main color information of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper -- Parameters - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | - | callback | AsyncCallback<Array<[RgbaColor](#rgbacolor)>> | Yes | Callback used to return the main color information of the wallpaper. | +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | +| callback | AsyncCallback<Array<[RgbaColor](#rgbacolor)>> | Yes | Callback used to return the main color information of the wallpaper. | + +**Example** -- Example - ```js wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { if (error) { @@ -56,7 +55,7 @@ Obtains the main color information of the wallpaper of a specified type. getColors(wallpaperType: WallpaperType): Promise<Array<RgbaColor>> -Obtains the main color information of the wallpaper of a specified type. +Obtains the main color information of the wallpaper of the specified type. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -74,20 +73,20 @@ Obtains the main color information of the wallpaper of a specified type. **Example** -```js -wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to getColors.`); -}).catch((error) => { - console.error(`failed to getColors because: ` + JSON.stringify(error)); -}); -``` + ```js + wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getColors.`); + }).catch((error) => { + console.error(`failed to getColors because: ` + JSON.stringify(error)); + }); + ``` ## wallpaper.getId getId(wallpaperType: WallpaperType, callback: AsyncCallback<number>): void -Obtains the ID of the wallpaper of the specified type. +Obtains the ID of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -100,25 +99,26 @@ Obtains the ID of the wallpaper of the specified type. **Example** -```js -wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to getId because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getId: ` + JSON.stringify(data)); -}); -``` + ```js + wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to getId because: ` + JSON.stringify(error)); + return; + } + console.log(`success to getId: ` + JSON.stringify(data)); + }); + ``` ## wallpaper.getId getId(wallpaperType: WallpaperType): Promise<number> -Obtains the ID of the wallpaper of the specified type. +Obtains the ID of the wallpaper of the specified type. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper + **Parameters** | Name | Type | Mandatory | Description | @@ -133,20 +133,20 @@ Obtains the ID of the wallpaper of the specified type. **Example** -```js -wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to getId: ` + JSON.stringify(data)); -}).catch((error) => { - console.error(`failed to getId because: ` + JSON.stringify(error)); -}); -``` + ```js + wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getId: ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to getId because: ` + JSON.stringify(error)); + }); + ``` ## wallpaper.getMinHeight getMinHeight(callback: AsyncCallback<number>): void -Obtains the minimum height of the wallpaper. +Obtains the minimum height of this wallpaper. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -158,25 +158,26 @@ Obtains the minimum height of the wallpaper. **Example** -```js -wallpaper.getMinHeight((error, data) => { - if (error) { - console.error(`failed to getMinHeight because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getMinHeight: ` + JSON.stringify(data)); -}); -``` + ```js + wallpaper.getMinHeight((error, data) => { + if (error) { + console.error(`failed to getMinHeight because: ` + JSON.stringify(error)); + return; + } + console.log(`success to getMinHeight: ` + JSON.stringify(data)); + }); + ``` ## wallpaper.getMinHeight getMinHeight(): Promise<number> -Obtains the minimum height of the wallpaper. +Obtains the minimum height of this wallpaper. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper + **Return value** | Type | Description | @@ -185,20 +186,20 @@ Obtains the minimum height of the wallpaper. **Example** -```js -wallpaper.getMinHeight().then((data) => { - console.log(`success to getMinHeight: ` + JSON.stringify(data)); -}).catch((error) => { - console.error(`failed to getMinHeight because: ` + JSON.stringify(error)); -}); -``` + ```js + wallpaper.getMinHeight().then((data) => { + console.log(`success to getMinHeight: ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to getMinHeight because: ` + JSON.stringify(error)); + }); + ``` ## wallpaper.getMinWidth getMinWidth(callback: AsyncCallback<number>): void -Obtains the minimum width of the wallpaper. +Obtains the minimum width of this wallpaper. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -210,22 +211,22 @@ Obtains the minimum width of the wallpaper. **Example** -```js -wallpaper.getMinWidth((error, data) => { - if (error) { - console.error(`failed to getMinWidth because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getMinWidth: ` + JSON.stringify(data)); -}); -``` + ```js + wallpaper.getMinWidth((error, data) => { + if (error) { + console.error(`failed to getMinWidth because: ` + JSON.stringify(error)); + return; + } + console.log(`success to getMinWidth: ` + JSON.stringify(data)); + }); + ``` ## wallpaper.getMinWidth getMinWidth(): Promise<number> -Obtains the minimum width of the wallpaper. +Obtains the minimum width of this wallpaper. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -237,20 +238,20 @@ Obtains the minimum width of the wallpaper. **Example** -```js -wallpaper.getMinWidth().then((data) => { - console.log(`success to getMinWidth: ` + JSON.stringify(data)); -}).catch((error) => { - console.error(`failed to getMinWidth because: ` + JSON.stringify(error)); -}); -``` + ```js + wallpaper.getMinWidth().then((data) => { + console.log(`success to getMinWidth: ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to getMinWidth because: ` + JSON.stringify(error)); + }); + ``` ## wallpaper.isChangePermitted isChangePermitted(callback: AsyncCallback<boolean>): void -Checks whether to allow the application to change the wallpaper for the current user. +Checks whether to allow the application to change the wallpaper for the current user. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -258,26 +259,26 @@ Checks whether to allow the application to change the wallpaper for the current | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the queried result. Returns **true** if it is allowed; returns **false** otherwise. | +| callback | AsyncCallback<boolean> | Yes | Returns **true** if the application is allowed to change the wallpaper for the current user; returns **false** otherwise. | **Example** -```js -wallpaper.isChangePermitted((error, data) => { - if (error) { - console.error(`failed to isChangePermitted because: ` + JSON.stringify(error)); - return; - } - console.log(`success to isChangePermitted: ` + JSON.stringify(data)); -}); -``` + ```js + wallpaper.isChangePermitted((error, data) => { + if (error) { + console.error(`failed to isChangePermitted because: ` + JSON.stringify(error)); + return; + } + console.log(`success to isChangePermitted: ` + JSON.stringify(data)); + }); + ``` ## wallpaper.isChangePermitted isChangePermitted(): Promise<boolean> -Checks whether to allow the application to change the wallpaper for the current user. +Checks whether to allow the application to change the wallpaper for the current user. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -285,24 +286,24 @@ Checks whether to allow the application to change the wallpaper for the current | Type | Description | | -------- | -------- | -| Promise<boolean> | Promise used to return whether to allow the application to change the wallpaper for the current user. Returns **true** if it is allowed; returns **false** otherwise. | +| Promise<boolean> | Returns **true** if the application is allowed to change the wallpaper for the current user; returns **false** otherwise. | **Example** -```js -wallpaper.isChangePermitted().then((data) => { - console.log(`success to isChangePermitted: ` + JSON.stringify(data)); -}).catch((error) => { - console.error(`failed to isChangePermitted because: ` + JSON.stringify(error)); -}); -``` + ```js + wallpaper.isChangePermitted().then((data) => { + console.log(`success to isChangePermitted: ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to isChangePermitted because: ` + JSON.stringify(error)); + }); + ``` ## wallpaper.isOperationAllowed isOperationAllowed(callback: AsyncCallback<boolean>): void -Checks whether the user is allowed to set wallpapers. +Checks whether the user is allowed to set wallpapers. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -310,26 +311,26 @@ Checks whether the user is allowed to set wallpapers. | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return whether the user is allowed to set wallpapers. Returns **true** if it is allowed; returns **false** otherwise. | +| callback | AsyncCallback<boolean> | Yes | Returns **true** if the user is allowed to set wallpapers; returns **false** otherwise. | **Example** -```js -wallpaper.isOperationAllowed((error, data) => { - if (error) { - console.error(`failed to isOperationAllowed because: ` + JSON.stringify(error)); - return; - } - console.log(`success to isOperationAllowed: ` + JSON.stringify(data)); -}); -``` + ```js + wallpaper.isOperationAllowed((error, data) => { + if (error) { + console.error(`failed to isOperationAllowed because: ` + JSON.stringify(error)); + return; + } + console.log(`success to isOperationAllowed: ` + JSON.stringify(data)); + }); + ``` ## wallpaper.isOperationAllowed isOperationAllowed(): Promise<boolean> -Checks whether the user is allowed to set wallpapers. +Checks whether the user is allowed to set wallpapers. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -337,26 +338,26 @@ Checks whether the user is allowed to set wallpapers. | Type | Description | | -------- | -------- | -| Promise<boolean> | Promise used to return whether the user is allowed to set wallpapers. Returns **true** if it is allowed; returns **false** otherwise. | +| Promise<boolean> | Returns **true** if the user is allowed to set wallpapers; returns **false** otherwise. | **Example** -```js -wallpaper.isOperationAllowed().then((data) => { - console.log(`success to isOperationAllowed: ` + JSON.stringify(data)); -}).catch((error) => { - console.error(`failed to isOperationAllowed because: ` + JSON.stringify(error)); -}); -``` + ```js + wallpaper.isOperationAllowed().then((data) => { + console.log(`success to isOperationAllowed: ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to isOperationAllowed because: ` + JSON.stringify(error)); + }); + ``` ## wallpaper.reset reset(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void -Removes a wallpaper of the specified type and restores the default one. +Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.SET_WALLPAPER +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -365,28 +366,28 @@ Removes a wallpaper of the specified type and restores the default one. | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, the result of removal is returned. Otherwise, error information is returned. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned. | **Example** -```js -wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to reset because: ` + JSON.stringify(error)); - return; - } - console.log(`success to reset.`); -}); -``` + ```js + wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to reset because: ` + JSON.stringify(error)); + return; + } + console.log(`success to reset.`); + }); + ``` ## wallpaper.reset reset(wallpaperType: WallpaperType): Promise<void> -Removes a wallpaper of the specified type and restores the default one. +Resets the wallpaper of the specified type to the default wallpaper. This API uses a promise to return the result. -**Required permission**: ohos.permission.SET_WALLPAPER +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -400,26 +401,26 @@ Removes a wallpaper of the specified type and restores the default one. | Type | Description | | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the result of removal is returned. Otherwise, error information is returned. | +| Promise<void> | Promise used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned. | **Example** -```js -wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to reset.`); -}).catch((error) => { - console.error(`failed to reset because: ` + JSON.stringify(error)); -}); -``` + ```js + wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to reset.`); + }).catch((error) => { + console.error(`failed to reset because: ` + JSON.stringify(error)); + }); + ``` ## wallpaper.setWallpaper setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void -Sets a specified source as the wallpaper of a specified type. +Sets a specified source as the wallpaper of a specified type. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.SET_WALLPAPER +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -427,7 +428,7 @@ Sets a specified source as the wallpaper of a specified type. | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| source | string \| [PixelMap](js-apis-image.md#pixelmap7) | Yes | URI path of the JPEG or PNG file, or bitmap of the PNG file. | +| source | string \| [PixelMap](js-apis-image.md#pixelmap7) | Yes | URI of a JPEG or PNG file, or bitmap of a PNG file. | | wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned. | @@ -435,45 +436,45 @@ Sets a specified source as the wallpaper of a specified type. ```js // The source type is string. -let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; -wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); - return; - } - console.log(`success to setWallpaper.`); -}); - + let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; + wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); + return; + } + console.log(`success to setWallpaper.`); + }); + // The source type is image.PixelMap. -import image from '@ohos.multimedia.image'; -let imageSource = image.createImageSource("file://" + wallpaperPath); -let opts = { - "desiredSize": { - "height": 3648, - "width": 2736 - } -}; -imageSource.createPixelMap(opts).then((pixelMap) => { - wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); - return; - } - console.log(`success to setWallpaper.`); - }); -}).catch((error) => { - console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); -}); -``` + import image from '@ohos.multimedia.image'; + let imageSource = image.createImageSource("file://" + wallpaperPath); + let opts = { + "desiredSize": { + "height": 3648, + "width": 2736 + } + }; + imageSource.createPixelMap(opts).then((pixelMap) => { + wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); + return; + } + console.log(`success to setWallpaper.`); + }); + }).catch((error) => { + console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); + }); + ``` ## wallpaper.setWallpaper setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise<void> -Sets a specified source as the wallpaper of a specified type. +Sets a specified source as the wallpaper of a specified type. This API uses a promise to return the result. -**Required permission**: ohos.permission.SET_WALLPAPER +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -494,38 +495,38 @@ Sets a specified source as the wallpaper of a specified type. ```js // The source type is string. -let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; -wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to setWallpaper.`); -}).catch((error) => { - console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); -}); - + let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; + wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to setWallpaper.`); + }).catch((error) => { + console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); + }); + // The source type is image.PixelMap. -import image from '@ohos.multimedia.image'; -let imageSource = image.createImageSource("file://" + wallpaperPath); -let opts = { - "desiredSize": { - "height": 3648, - "width": 2736 - } -}; -imageSource.createPixelMap(opts).then((pixelMap) => { - wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to setWallpaper.`); - }).catch((error) => { - console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); - }); -}).catch((error) => { - console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); -}); -``` + import image from '@ohos.multimedia.image'; + let imageSource = image.createImageSource("file://" + wallpaperPath); + let opts = { + "desiredSize": { + "height": 3648, + "width": 2736 + } + }; + imageSource.createPixelMap(opts).then((pixelMap) => { + wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to setWallpaper.`); + }).catch((error) => { + console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); + }); + }).catch((error) => { + console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); + }); + ``` ## wallpaper.getFile8+ getFile(wallpaperType: WallpaperType, callback: AsyncCallback<number>): void -Obtains the wallpaper of the specified type. +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 @@ -540,23 +541,23 @@ Obtains the wallpaper of the specified type. **Example** -```js -wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to getFile because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getFile: ` + JSON.stringify(data)); -}); -``` + ```js + wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to getFile because: ` + JSON.stringify(error)); + return; + } + console.log(`success to getFile: ` + JSON.stringify(data)); + }); + ``` ## wallpaper.getFile8+ getFile(wallpaperType: WallpaperType): Promise<number> -Obtains the wallpaper of the specified type. +Obtains the wallpaper of the specified type. This API uses a promise to return the result. -**Required permissions**: ohos.permission.GET_WALLPAPER and ohos.permission.READ_USER_STORAGE +**Required permissions**: ohos.permission.SET_WALLPAPER and ohos.permission.READ_USER_STORAGE **System capability**: SystemCapability.MiscServices.Wallpaper @@ -574,13 +575,75 @@ Obtains the wallpaper of the specified type. **Example** -```js -wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to getFile: ` + JSON.stringify(data)); -}).catch((error) => { - console.error(`failed to getFile because: ` + JSON.stringify(error)); -}); -``` + ```js + wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getFile: ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to getFile because: ` + JSON.stringify(error)); + }); + ``` + + +## wallpaper.getPixelMap + +getPixelMap(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; + +Obtains the pixel image for the wallpaper of the specified type. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WALLPAPER and ohos.permission.READ_USER_STORAGE + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned.| + +**Example** + + ```js + wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (err, data) { + console.info('wallpaperXTS ===> testGetPixelMapCallbackSystem err : ' + JSON.stringify(err)); + console.info('wallpaperXTS ===> testGetPixelMapCallbackSystem data : ' + JSON.stringify(data)); + }); + ``` + + +## wallpaper.getPixelMap + +getPixelMap(wallpaperType: WallpaperType): Promise<image.PixelMap> + +Obtains the pixel image for the wallpaper of the specified type. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WALLPAPER and ohos.permission.READ_USER_STORAGE + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned.| + +**Example** + + ```js + wallpaper.getPixelMap(WALLPAPER_SYSTEM).then((data) => { + console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem data : ' + data); + console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem data : ' + JSON.stringify(data)); + }).catch((err) => { + console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem err : ' + err); + console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem err : ' + JSON.stringify(err)); + }); + ``` ## wallpaper.on('colorChange') @@ -596,16 +659,16 @@ Subscribes to the wallpaper color change event. | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Type of the event to subscribe to. The value **colorChange** indicates subscribing to the wallpaper color change event. | -| callback | function | Yes | Callback triggered when the wallpaper color changes. The wallpaper type and main colors are returned.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type. | +| callback | function | Yes | Callback triggered when the wallpaper color changes. The wallpaper type and main colors are returned.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type. | **Example** -```js -let listener = (colors, wallpaperType) => { - console.log(`wallpaper color changed.`); -}; -wallpaper.on('colorChange', listener); -``` + ```js + let listener = (colors, wallpaperType) => { + console.log(`wallpaper color changed.`); + }; + wallpaper.on('colorChange', listener); + ``` ## wallpaper.off('colorChange') @@ -621,15 +684,15 @@ Unsubscribes from the wallpaper color change event. | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Type of the event to unsubscribe from. The value **colorChange** indicates unsubscribing from the wallpaper color change event. | -| callback | function | No | Callback for the wallpaper color change event. If this parameter is not specified, all callbacks corresponding to the wallpaper color change event are invoked.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type. | +| callback | function | No | Callback for the wallpaper color change event. If this parameter is not specified, all callbacks corresponding to the wallpaper color change event are invoked.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type. | **Example** -```js -let listener = (colors, wallpaperType) => { - console.log(`wallpaper color changed.`); -}; -wallpaper.on('colorChange', listener); + ```js + let listener = (colors, wallpaperType) => { + console.log(`wallpaper color changed.`); + }; + wallpaper.on('colorChange', listener); // Unsubscribe from the listener. wallpaper.off('colorChange', listener); //Unsubscribe from all subscriptions of the colorChange type. diff --git a/en/application-dev/reference/apis/js-apis-wantAgent.md b/en/application-dev/reference/apis/js-apis-wantAgent.md index f54e0769783406311f1127adc6891d7d997c5b51..c6a89b78715f1a819cd04a11f67a0609a98aa4f9 100644 --- a/en/application-dev/reference/apis/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-wantAgent.md @@ -1,8 +1,8 @@ -# WantAgent Module +# WantAgent ->**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 @@ -782,7 +782,7 @@ Checks whether two **WantAgent** objects are equal. This API uses an asynchronou | Name | Readable| Writable| Type | Mandatory| Description | | ---------- | --- | ---- | ------------------------ | ---- | --------------------------------------- | | agent | Yes | No | WantAgent | Yes | The first **WantAgent** object. | -| otherAgent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | +| otherAgent | Yes | No | WantAgent | Yes | The second **WantAgent** object. | | callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -857,7 +857,7 @@ Checks whether two **WantAgent** objects are equal. This API uses a promise to r | Name | Readable| Writable| Type | Mandatory| Description | | ---------- | --- | ---- | --------- | ---- | ------------- | | agent | Yes | No | WantAgent | Yes | The first **WantAgent** object.| -| otherAgent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| +| otherAgent | Yes | No | WantAgent | Yes | The second **WantAgent** object.| **Return value** @@ -914,7 +914,7 @@ WantAgent.equal(wantAgent1, wantAgent2).then((data) => { }); ``` -## WantAgent.getOperationType +## WantAgent.getOperationType9+ getOperationType(agent: WantAgent, callback: AsyncCallback\): void; @@ -975,7 +975,7 @@ WantAgent.getOperationType(wantAgent, (OperationType) => { }) ``` -## WantAgent.getOperationType +## WantAgent.getOperationType9+ getOperationType(agent: WantAgent): Promise\; diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index edf6be53ac623c5fa4a8f1542bf7222dc42e713c..52f5367110bc35c33075ed291a796a657a468816 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -23,7 +23,7 @@ import webSocket from '@ohos.net.webSocket'; var defaultIpAddress = "ws://"; let ws = webSocket.createWebSocket(); ws.on('open', (err, value) => { - console.log("on open, status:" + value.status + ", message:" + value.message); + console.log("on open, status:" + value['status'] + ", message:" + value['message']); // 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) { @@ -47,7 +47,7 @@ ws.on('message', (err, value) => { } }); ws.on('close', (err, value) => { - console.log("on close, code is " + value.code + ", reason is " + value.reason); + console.log("on close, code is " + value['code'] + ", reason is " + value['reason']); }); ws.on('error', (err) => { console.log("on error, error:" + JSON.stringify(err)); @@ -393,7 +393,7 @@ Enables listening for the **open** events of a WebSocket connection. This API us ```js let ws = webSocket.createWebSocket(); ws.on('open', (err, value) => { - console.log("on open, status:" + value.status + ", message:" + value.message); + console.log("on open, status:" + value['status'] + ", message:" + value['message']); }); ``` @@ -421,7 +421,7 @@ Disables listening for the **open** events of a WebSocket connection. This API u ```js let ws = webSocket.createWebSocket(); let callback1 = (err, value) => { - console.log("on open, status:" + value.status + ", message:" + value.message); + console.log("on open, status:" + value['status'] + ", message:" + value['message']); } ws.on('open', callback1); // You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. @@ -505,7 +505,7 @@ Enables listening for the **close** events of a WebSocket connection. This API u ```js let ws = webSocket.createWebSocket(); ws.on('close', (err, value) => { - console.log("on close, code is " + value.code + ", reason is " + value.reason); + console.log("on close, code is " + value['code'] + ", reason is " + value['reason']); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-webgl.md b/en/application-dev/reference/apis/js-apis-webgl.md index 5538e471be7bc9d6541a54438f9eb0008483b170..bf13c3d9188fe48996c9f56342af8436bb398b9e 100644 --- a/en/application-dev/reference/apis/js-apis-webgl.md +++ b/en/application-dev/reference/apis/js-apis-webgl.md @@ -12,7 +12,8 @@ This module provides WebGL APIs that correspond to the OpenGL ES 2.0 feature set Create a **** component in the HML file. The following is an example: -``` +```html +
diff --git a/en/application-dev/reference/apis/js-apis-webgl2.md b/en/application-dev/reference/apis/js-apis-webgl2.md index 85559c1a9fcff3f4ac093fb4cf00957972f05145..12cc9789b84cd85960154cd1de1994c8a9f12331 100644 --- a/en/application-dev/reference/apis/js-apis-webgl2.md +++ b/en/application-dev/reference/apis/js-apis-webgl2.md @@ -12,7 +12,8 @@ This module provides WebGL APIs that correspond to the OpenGL ES 3.0 feature set Create a **** component in the HML file. The following is an example: -``` +```html +
diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index c4d8d105f13c4214912120eb9fc1659276ba07be..503ee06a8f8546cb1386b67b863fe3e6bd16f7aa 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -589,7 +589,7 @@ Represents the P2P device information. | deviceAddress | string | Read only| MAC address of the device.| | primaryDeviceType | string | Read only| Type of the primary device.| | deviceStatus | [P2pDeviceStatus](#P2pDeviceStatus) | Read only| Device status.| -| groupCapabilities | number | Read only| Group capabilities.| +| groupCapabilitys | number | Read only| Group capabilities.| ## P2pDeviceStatus8+ diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 9c23173a74ce036859f2b8cecdb83f541da4c463..885802b44997a358ec30fa363fc292d1efa6971c 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -18,10 +18,23 @@ Enumerates the window types. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Default Value| Description | +| Name | Default Value | Description | | ----------------- | ------ | ------------------ | | TYPE_APP | 0 | Application subwindow. | | TYPE_SYSTEM_ALERT | 1 | System alert window.| +| TYPE_INPUT_METHOD9+ | 2 | Input method window.| +| TYPE_STATUS_BAR9+ | 3 | Status bar.| +| TYPE_PANEL9+ | 4 | Notification panel.| +| TYPE_KEYGUARD9+ | 5 | Lock screen.| +| TYPE_VOLUME_OVERLAY9+ | 6 | Volume bar.| +| TYPE_NAVIGATION_BAR9+ | 7 | Navigation bar.| +| TYPE_FLOAT9+ | 8 | Floating window.| +| TYPE_WALLPAPER9+ | 9 | Wallpaper.| +| TYPE_DESKTOP9+ | 10 | Home screen.| +| TYPE_LAUNCHER_RECENT9+ | 11 | Recent tasks screen.| +| TYPE_LAUNCHER_DOCK9+ | 12 | Dock bar on the home screen.| +| TYPE_VOICE_INTERACTION9+ | 13 | Voice assistant.| +| TYPE_POINTER9+ | 14 | Mouse.| ## AvoidAreaType7+ @@ -29,7 +42,7 @@ Enumerates the types of the area where the window cannot be displayed. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Default Value| Description | +| Name | Default Value | Description | | ----------- | ------ | ------------------ | | TYPE_SYSTEM | 0 | Default area of the system.| | TYPE_CUTOUT | 1 | Notch. | @@ -42,7 +55,7 @@ This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Default Value| Description | +| Name | Default Value | Description | | ---------- | ------ | ----------------------------- | | UNDEFINED | 1 | The window mode is not defined by the application. | | FULLSCREEN | 2 | The application is displayed in full screen. | @@ -158,7 +171,7 @@ Describes the color gamut mode. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Default Value| Description | +| Name | Default Value | Description | | ---------- | ------ | -------------- | | DEFAULT | 0 | Default color gamut mode.| | WIDE_GAMUT | 1 | Wide color gamut mode. | @@ -236,9 +249,7 @@ This API is deprecated since API version 8. You are advised to use [window.creat create(ctx: Context, id: string, type: WindowType, callback: AsyncCallback<Window>): void -Creates a subwindow when the context is [Context](js-apis-Context.md). This API uses an asynchronous callback to return the result. - -Creates a system window when the context is [ServiceExtensionContext](js-apis-service-extension-context.md). This API uses an asynchronous callback to return the result. It is valid since API version 9. +Creates a subwindow (in API version 8) or a system window (from API version 9). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -246,7 +257,7 @@ Creates a system window when the context is [ServiceExtensionContext](js-apis-se | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).
For the definition of **Context** of API version 9, see [Context](js-apis-service-extension-context.md).| +| ctx | Context | Yes | Current application context.
For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).
For the definition of **Context** of API version 9, see [ServiceExtensionContext](js-apis-service-extension-context.md).| | id | string | Yes | Window ID. | | type | [WindowType](#windowtype) | Yes | Window type. | | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the window created. | @@ -270,9 +281,7 @@ Creates a system window when the context is [ServiceExtensionContext](js-apis-se create(ctx: Context, id: string, type: WindowType): Promise<Window> -Creates a subwindow when the context is [Context](js-apis-Context.md). This API uses a promise to return the result. - -Creates a system window when the context is [ServiceExtensionContext](js-apis-service-extension-context.md). This API uses a promise to return the result. It is valid since API version 9. +Creates a subwindow (in API version 8) or a system window (from API version 9). This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -280,7 +289,7 @@ Creates a system window when the context is [ServiceExtensionContext](js-apis-se | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).
For the definition of **Context** of API version 9, see [Context](js-apis-service-extension-context.md).| +| ctx | Context | Yes | Current application context.
For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).
For the definition of **Context** of API version 9, see [ServiceExtensionContext](js-apis-service-extension-context.md).| | id | string | Yes | Window ID. | | type | [WindowType](#windowtype) | Yes | Window type. | @@ -436,7 +445,7 @@ Obtains the top window of the current application. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).
For the definition of **Context** of API version 9, see [Context](js-apis-ability-context.md).| +| ctx | Context | Yes | Current application context.
For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).
For the definition of **Context** of API version 9, see [AbilityContext](js-apis-ability-context.md). | | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained. | **Example** @@ -465,7 +474,7 @@ Obtains the top window of the current application. This API uses a promise to re | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).
For the definition of **Context** of API version 9, see [Context](js-apis-ability-context.md).| +| ctx | Context | Yes | Current application context.
For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).
For the definition of **Context** of API version 9, see [AbilityContext](js-apis-ability-context.md). | **Return value** @@ -1783,8 +1792,9 @@ setDimBehind(dimBehindValue: number, callback: AsyncCallback<void>): void Sets the dimness of the window that is not on top. This API uses an asynchronous callback to return the result. -> This API is supported since API version 7 and deprecated since API version 9. +> **NOTE** > +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1813,8 +1823,9 @@ setDimBehind(dimBehindValue: number): Promise<void> Sets the dimness of the window that is not on top. This API uses a promise to return the result. -> This API is supported since API version 7 and deprecated since API version 9. +> **NOTE** > +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1935,8 +1946,9 @@ setOutsideTouchable(touchable: boolean, callback: AsyncCallback<void>): vo Sets whether the area outside the subwindow is touchable. This API uses an asynchronous callback to return the result. -> This API is supported since API version 7 and deprecated since API version 9. +> **NOTE** > +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1965,8 +1977,9 @@ setOutsideTouchable(touchable: boolean): Promise<void> Sets whether the area outside the subwindow is touchable. This API uses a promise to return the result. -> This API is supported since API version 7 and deprecated since API version 9. +> **NOTE** > +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2153,7 +2166,7 @@ Describes the lifecycle of a window stage. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Default Value| Description | +| Name | Default Value | Description | | ---------- | ------ | -------- | | FOREGROUND | 1 | The window stage is running in the foreground.| | ACTIVE | 2 | The window stage gains focus.| @@ -2454,3 +2467,28 @@ Disables listening for window stage lifecycle changes. } } ``` + +### setShowOnLockScreen('showOnLockScreen')9+ + +setShowOnLockScreen(showOnLockScreen: boolean): void + +Sets whether to display the window of the application on the lock screen. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------------- | ------- | ---- | ---------------------------- | +| showOnLockScreen | boolean | Yes | Whether to display the window on the lock screen.| + +**Example** + +```ts +class myAbility extends Ability { + onWindowStageCreate(windowStage) { + console.log('onWindowStageCreate'); + windowStage.setShowOnLockScreen(true); + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index c014e5dbbef4cd972a9af5bb77efd71c3c363ae3..f22c9988cf123f79225babf014b089bb98e6247a 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -55,6 +55,8 @@ Sets an attribute. **Example** ```js +var arrayBuffer = new ArrayBuffer(1024); +var bufView = new DataView(arrayBuffer); var thatSer = new xml.XmlSerializer(bufView); thatSer.setAttributes("importance", "high"); ``` @@ -77,6 +79,8 @@ Adds an empty element. **Example** ```js +var arrayBuffer = new ArrayBuffer(1024); +var bufView = new DataView(arrayBuffer); var thatSer = new xml.XmlSerializer(bufView); thatSer.addEmptyElement("b"); // => ``` @@ -93,6 +97,8 @@ Sets a declaration. **Example** ```js +var arrayBuffer = new ArrayBuffer(1024); +var bufView = new DataView(arrayBuffer); var thatSer = new xml.XmlSerializer(bufView); thatSer.setDeclaration() // => ; ``` @@ -133,6 +139,8 @@ Writes the end tag of the element. **Example** ```js +var arrayBuffer = new ArrayBuffer(1024); +var bufView = new DataView(arrayBuffer); var thatSer = new xml.XmlSerializer(bufView); thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); thatSer.startElement("table"); diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index 2bf27848a2ed6025b0a8f7f961582aceec093372..939fc0d2dbcc0e97fbb1ae8bd1112fd7aa2acc9f 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -1,7 +1,5 @@ # Zip Module (JavaScript SDK APIs) -## Constraints -None ## Modules to Import ```javascript @@ -9,7 +7,9 @@ import zlib from '@ohos.zlib'; ``` ## zlib.zipFile -zipFile(inFile:string, outFile:string, options: Options): Promise; + +zipFile(inFile:string, outFile:string, options: Options): Promise\ + Zips a file. This API uses a promise to return the result. **System capability**: SystemCapability.BundleManager.Zlib @@ -36,17 +36,14 @@ Zips a file. This API uses a promise to return the result. import zlib from '@ohos.zlib' var inFile = "/xxx/filename.xxx"; var outFile = "/xxx/xxx.zip"; -var options = {}; -options.level = zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION; -options.memLevel = zlib.MemLevel.MEM_LEVEL_DEFAULT; -options.strategy = zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY; +var options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY +}; zlib.zipFile(inFile, outFile, options).then((data) => { - if (data == zlib.ErrorCode.ERROR_CODE_OK) { - console.log("zipFile OK"); - } else { - console.log("zipFile NG"); - } + console.log("zipFile result: " + data); }).catch((err)=>{ console.log("catch((err)=>" + err); }); @@ -60,17 +57,14 @@ zlib.zipFile(inFile, outFile, options).then((data) => { import zlib from '@ohos.zlib' var inFile = "/xxx/xxx"; var outFile = "/xxx/xxx.zip"; -var options = {}; -options.level = zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION; -options.memLevel = zlib.MemLevel.MEM_LEVEL_DEFAULT; -options.strategy = zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY; - -zlib.zipFile(inFile , unzipDir, options).then((data) => { - if (data == zlib.ErrorCode.ERROR_CODE_OK) { - console.log("zipFile OK"); - } else { - console.log("zipFile NG"); - } +var options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY +}; + +zlib.zipFile(inFile , outFile, options).then((data) => { + console.log("zipFile result: " + data); }).catch((err)=>{ console.log("catch((err)=>" + err); }); @@ -78,7 +72,7 @@ zlib.zipFile(inFile , unzipDir, options).then((data) => { ## zlib.unzipFile -unzipFile(inFile:string, outFile:string, options: Options): Promise; +unzipFile(inFile:string, outFile:string, options: Options): Promise\ Unzips a file. This API uses a promise to return the result. @@ -88,7 +82,7 @@ Unzips a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ----------------------------------- | ---- | ----------------------------------- | -| inFile | string | Yes | Path of the file to unzip. The file name extension is .zip.| +| inFile | string | Yes | Path of the .zip file to unzip.| | outFile | string | Yes | Path of the unzipped file. | | options | [Options](#options)| No | Optional parameters for the unzip operation. | @@ -106,30 +100,26 @@ import zlib from '@ohos.zlib' var inFile = "/xx/xxx.zip"; var outFile = "/xxx"; -var options = {}; -options.level = zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION; -options.memLevel = zlib.MemLevel.MEM_LEVEL_DEFAULT; -options.strategy = zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY; - +let options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY +}; zlib.unzipFile(inFile, outFile, options).then((data) => { - if (data == zlib.ErrorCode.ERROR_CODE_OK) { - console.log("unzipFile OK"); - } else { - console.log("unzipFile NG"); - } + console.log("unzipFile result: " + data); }).catch((err)=>{ console.log("catch((err)=>" + err); }) ``` -## options +## Options | Name | Description | | --------------------------- | ------------------------------------------------------------ | -| level?: CompressLeve | See [zip.CompressLevel](##zipcompresslevel). | -| memLevel?: MemLevel | See [zip.MemLevel](#zipmemlevel) | -| strategy?: CompressStrategy | See [zip.CompressStrategy](#zipcompressstrategy) | +| level?: CompressLeve | See [zip.CompressLevel](#zipcompresslevel).| +| memLevel?: MemLevel | See [zip.MemLevel](#zipmemlevel). | +| strategy?: CompressStrategy | See [zip.CompressStrategy](#zipcompressstrategy).| ## zip.MemLevel @@ -143,24 +133,24 @@ zlib.unzipFile(inFile, outFile, options).then((data) => { | Name | Description | | --------------------------------------- | ----------------- | -| COMPRESS_LEVEL_NO_COMPRESSION : 0 | Compress level 0 that indicates uncompressed.| -| COMPRESS_LEVEL_BEST_SPEED : 1 | Compression level 1 that gives the best speed. | -| COMPRESS_LEVEL_BEST_COMPRESSION :9 | Compression level 9 that gives the best compression. | -| COMPRESS_LEVEL_DEFAULT_COMPRESSION : -1| Default compression level. | +| COMPRESS_LEVEL_NO_COMPRESSION: 0 | Compress level 0 that indicates uncompressed.| +| COMPRESS_LEVEL_BEST_SPEED: 1 | Compression level 1 that gives the best speed. | +| COMPRESS_LEVEL_BEST_COMPRESSION: 9 | Compression level 9 that gives the best compression. | +| COMPRESS_LEVEL_DEFAULT_COMPRESSION: -1| Default compression level. | ## Zip.CompressStrategy | Name | Description | | -------------------------------------- | ------------------------ | -| COMPRESS_STRATEGY_DEFAULT_STRATEGY : 0 | Default compression strategy. | -| COMPRESS_STRATEGY_FILTERED : 1 | Filtered compression strategy.| -| COMPRESS_STRATEGY_HUFFMAN_ONLY : 2 | Huffman coding compression strategy. | -| COMPRESS_STRATEGY_RLE : 3 | RLE compression strategy. | -| COMPRESS_STRATEGY_FIXED : 4 | Fixed compression strategy. | +| COMPRESS_STRATEGY_DEFAULT_STRATEGY: 0 | Default compression strategy. | +| COMPRESS_STRATEGY_FILTERED: 1 | Filtered compression strategy.| +| COMPRESS_STRATEGY_HUFFMAN_ONLY: 2 | Huffman coding compression strategy. | +| COMPRESS_STRATEGY_RLE: 3 | RLE compression strategy. | +| COMPRESS_STRATEGY_FIXED: 4 | Fixed compression strategy. | ## zip.ErrorCode | Name | Description | | -------------------- | ------------ | -| ERROR_CODE_OK: 0 | The API is successfully called.| -| ERROR_CODE_ERRNO:- 1 | Failed to call the API.| +| ERROR_CODE_OK: 0 | The API is successfully called.| +| ERROR_CODE_ERRNO: -1| Failed to call the API.| diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md index 8e7eff04944f47fa1e8aede82e2a06bf7dada901..d8812c8f318da2d756665722e3ec0563c641d52a 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md @@ -1,13 +1,13 @@ # CanvasRenderingContext2D -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> Supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. +> **NOTE**
+> Supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. **CanvasRenderingContext2D** allows you to draw rectangles, text, images, and other objects on a canvas. -- Example - ``` +**Example** + ```html
@@ -16,7 +16,7 @@
``` - ``` + ```js // xxx.js export default { handleClick() { @@ -47,39 +47,38 @@ ## Attributes -| Name | Type | Default Value | Description | -| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------- | ------------------------------------------------------------ | -| [fillStyle](#fillstyle) | \ \| [CanvasGradient](../arkui-js/js-components-canvas-canvasgradient.md) \| CanvasPattern | - | Style to fill an area.
- When the type is **<color>**, this parameter indicates the color of the filling area.
- When the type is **CanvasGradient**, this parameter indicates a gradient object, which is created using the **createLinearGradient()** method.
- When the type is **CanvasPattern**, this parameter indicates a canvas pattern, which is created using the **createPattern()** method. | -| [lineWidth](#linewidth) | number | - | Line width. | -| [strokeStyle](#strokestyle) | \ \| [CanvasGradient](../arkui-js/js-components-canvas-canvasgradient.md) \| CanvasPattern | - | Stroke style.
- When the type is **<color>**, this parameter indicates the stroke color.
- When the type is **CanvasGradient**, this parameter indicates a gradient object, which is created using the **createLinearGradient()** method.
- When the type is **CanvasPattern**, this parameter indicates a canvas pattern, which is created using the **createPattern()** method. | -| [lineCap](#linecap) | string | butt | Style of the specified line endpoint. The options are as follows:
- **butt**: The endpoints of the line are squared off.
- **round**: The endpoints of the line are rounded.
- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness. | -| [lineJoin](#linejoin) | string | miter | Style of the intersection point between line segments. The options are as follows:
- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.
- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.
- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**. | -| [miterLimit](#miterlimit) | number | 10 | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet. | +| Name | Type | Default Value | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | ---------------------------------------------- | ------------------------------------------------------------ | +| [fillStyle](#fillstyle) | \ \| [CanvasGradient](../arkui-js/js-components-canvas-canvasgradient.md) \| CanvasPattern | - | Style to fill an area.
- When the type is **\**, this parameter indicates the color of the filling area.
- When the type is **CanvasGradient**, this parameter indicates a gradient object, which is created using the **createLinearGradient()** method.
- When the type is **CanvasPattern**, this parameter indicates a canvas pattern, which is created using the **createPattern()** method. | +| [lineWidth](#linewidth) | number | - | Line width. | +| [strokeStyle](#strokestyle) | \ \| [CanvasGradient](../arkui-js/js-components-canvas-canvasgradient.md) \| CanvasPattern | - | Stroke style.
- When the type is **\**, this parameter indicates the stroke color.
- When the type is **CanvasGradient**, this parameter indicates a gradient object, which is created using the **createLinearGradient()** method.
- When the type is **CanvasPattern**, this parameter indicates a canvas pattern, which is created using the **createPattern()** method. | +| [lineCap](#linecap) | string | butt | Style of the specified line endpoint. The options are as follows:
- **butt**: The endpoints of the line are squared off.
- **round**: The endpoints of the line are rounded.
- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness. | +| [lineJoin](#linejoin) | string | miter | Style of the intersection point between line segments. The options are as follows:
- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.
- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.
- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**. | +| [miterLimit](#miterlimit) | number | 10 | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet. | | [font](#font) | string | "normal normal 14px sans-serif" | Font style.
Syntax: ctx.font="font-style font-weight font-size font-family"5+
- (Optional) **font-style**: font style. Available values are **normal** and **italic**.
- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**. | -| [textAlign](#textalign) | string | left | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
- **right**: The text is right-aligned.
- **center**: The text is center-aligned.
- **start**: The text is aligned with the start bound.
- **end**: The text is aligned with the end bound.
>![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> In the **ltr** layout mode, the value **start** equals **left**. In the **rtl** layout mode, the value **start** equals **right**. | -| [textBaseline](#textbaseline) | string | alphabetic | Horizontal alignment mode of text. Available values are as follows:
- **alphabetic**: The text baseline is the normal alphabetic baseline.
- **top**: The text baseline is on the top of the text bounding box.
- **hanging**: The text baseline is a hanging baseline over the text.
- **middle**: The text baseline is in the middle of the text bounding box.
- **ideographic**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excessive character.
- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line. | -| [globalAlpha](#globalalpha) | number | - | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque. | -| [lineDashOffset](#linedashoffset) | number | 0.0 | Offset of the dashed line. The precision is float. | -| [globalCompositeOperation](#globalcompositeoperation) | string | source-over | Composition operation type. Available values are as follows: source-over, source-atop, source-in, source-out, destination-over, destination-atop, destination-in, destination-out, lighter, copy, and xor. For details, see [Operation types](#globalcompositeoperation). | -| [shadowBlur](#shadowblur) | number | 0.0 | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float. | -| [shadowColor](#shadowcolor) | <color> | - | Shadow color. | -| [shadowOffsetX](#shadowoffsetx) | number | - | X-axis shadow offset relative to the original object. | -| [shadowOffsetY](#shadowoffsety) | number | - | Y-axis shadow offset relative to the original object. | -| [imageSmoothingEnabled](#imagesmoothingenabled6)6+ | boolean | true | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite. | +| [textAlign](#textalign) | string | left | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
- **right**: The text is right-aligned.
- **center**: The text is center-aligned.
- **start**: The text is aligned with the start bound.
- **end**: The text is aligned with the end bound.
In the **ltr** layout mode, the value **start** equals **left**. In the **rtl** layout mode, the value **start** equals **right**. | +| [textBaseline](#textbaseline) | string | alphabetic | Horizontal alignment mode of text. Available values are as follows:
- **alphabetic**: The text baseline is the normal alphabetic baseline.
- **top**: The text baseline is on the top of the text bounding box.
- **hanging**: The text baseline is a hanging baseline over the text.
- **middle**: The text baseline is in the middle of the text bounding box.
- **ideographic**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excessive character.
- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line. | +| [globalAlpha](#globalalpha) | number | - | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque. | +| [lineDashOffset](#linedashoffset) | number | 0.0 | Offset of the dashed line. The precision is float. | +| [globalCompositeOperation](#globalcompositeoperation) | string | source-over | Composition operation type. Available values are as follows: **source-over**, **source-atop**, **source-in**, **source-out**, **destination-over**, **destination-atop**, **destination-in**, **destination-out**, **lighter**, copy, and **xor**. For details, see [Operation types](#globalcompositeoperation). | +| [shadowBlur](#shadowblur) | number | 0.0 | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float. | +| [shadowColor](#shadowcolor) | <color> | - | Shadow color. | +| [shadowOffsetX](#shadowoffsetx) | number | - | X-axis shadow offset relative to the original object. | +| [shadowOffsetY](#shadowoffsety) | number | - | Y-axis shadow offset relative to the original object. | +| [imageSmoothingEnabled](#imagesmoothingenabled6)6+ | boolean | true | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite. | ### fillStyle - ``` + ```html -
``` -``` -//xxx.js +```js +// xxx.js export default { onShow() { const el =this.$refs.canvas; @@ -95,15 +94,15 @@ export default { ### lineWidth -``` +```html
``` -``` -//xxx.js +```js +// xxx.js export default { onShow() { const el =this.$refs.canvas; @@ -120,15 +119,15 @@ export default { ### strokeStyle -``` +```html
``` -``` -//xxx.js +```js +// xxx.js export default { onShow() { const el =this.$refs.canvas; @@ -145,15 +144,15 @@ export default { ### lineCap -``` +```html
``` -``` -//xxx.js +```js +// xxx.js export default { onShow() { const el =this.$refs.canvas; @@ -172,15 +171,15 @@ export default { ### lineJoin -``` +```html
``` -``` -//xxx.js +```js +// xxx.js export default { onShow() { const el =this.$refs.canvas; @@ -200,15 +199,15 @@ export default { ### miterLimit -``` +```html
``` -``` -//xxx.js +```js +// xxx.js export default { onShow() { const el =this.$refs.canvas; @@ -229,15 +228,15 @@ export default { ### font -``` +```html
``` -``` -//xxx.js +```js +// xxx.js export default { onShow() { const el =this.$refs.canvas; @@ -253,15 +252,15 @@ export default { ### textAlign -``` +```html
``` -``` -//xxx.js +```js +// xxx.js export default { onShow() { const el =this.$refs.canvas; @@ -292,15 +291,15 @@ export default { ### textBaseline -``` +```html
``` -``` -//xxx.js +```js +// xxx.js export default { onShow() { const el =this.$refs.canvas; @@ -328,15 +327,15 @@ export default { ### globalAlpha -``` +```html
``` -``` -//xxx.js +```js +// xxx.js export default { onShow() { const el =this.$refs.canvas; @@ -355,15 +354,15 @@ export default { ### lineDashOffset -``` +```html
``` -``` -//xxx.js +```js +// xxx.js export default { onShow() { const el =this.$refs.canvas; @@ -380,65 +379,66 @@ export default { ### globalCompositeOperation -- Operation types - | Value | Description | - | ---------------- | ------------------------ | - | source-over | Displays the new drawing above the existing drawing. This attribute is used by default. | - | source-atop | Displays the new drawing on the top of the existing drawing. | - | source-in | Displays the new drawing inside the existing drawing. | - | source-out | Displays part of the new drawing that is outside of the existing drawing. | - | destination-over | Displays the existing drawing above the new drawing. | - | destination-atop | Displays the existing drawing on the top of the new drawing. | - | destination-in | Displays the existing drawing inside the new drawing. | - | destination-out | Displays part of the existing drawing that is outside of the new drawing. | - | lighter | Displays both the new drawing and the existing drawing. | - | copy | Displays the new drawing and neglects the existing drawing. | - | xor | Combines the new drawing and existing drawing using the XOR operation.| - -- Example -``` - -
- -
+Operation types +| Value | Description | +| ---------------- | ------------------------ | +| source-over | Displays the new drawing above the existing drawing. This attribute is used by default. | +| source-atop | Displays the new drawing on the top of the existing drawing. | +| source-in | Displays the new drawing inside the existing drawing. | +| source-out | Displays part of the new drawing that is outside of the existing drawing. | +| destination-over | Displays the existing drawing above the new drawing. | +| destination-atop | Displays the existing drawing on the top of the new drawing. | +| destination-in | Displays the existing drawing inside the new drawing. | +| destination-out | Displays the existing drawing outside the new drawing. | +| lighter | Displays both the new and existing drawing. | +| copy | Displays the new drawing and neglects the existing drawing. | +| xor | Combines the new drawing and existing drawing using the XOR operation.| + +**Example** + +```html + +
+ +
``` - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.fillStyle = 'rgb(255,0,0)'; - ctx.fillRect(20, 20, 50, 50); - ctx.globalCompositeOperation = 'source-over'; - ctx.fillStyle = 'rgb(0,0,255)'; - ctx.fillRect(50, 50, 50, 50); - // Start drawing second example - ctx.fillStyle = 'rgb(255,0,0)'; - ctx.fillRect(120, 20, 50, 50); - ctx.globalCompositeOperation = 'destination-over'; - ctx.fillStyle = 'rgb(0,0,255)'; - ctx.fillRect(150, 50, 50, 50); - } + ```js +// xxx.js +export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.fillStyle = 'rgb(255,0,0)'; + ctx.fillRect(20, 20, 50, 50); + ctx.globalCompositeOperation = 'source-over'; + ctx.fillStyle = 'rgb(0,0,255)'; + ctx.fillRect(50, 50, 50, 50); + // Start drawing second example + ctx.fillStyle = 'rgb(255,0,0)'; + ctx.fillRect(120, 20, 50, 50); + ctx.globalCompositeOperation = 'destination-over'; + ctx.fillStyle = 'rgb(0,0,255)'; + ctx.fillRect(150, 50, 50, 50); } +} ``` ![en-us_image_0000001213192781](figures/en-us_image_0000001213192781.png) - In the above example, the blue rectangle represents the new drawing, and the red rectangle represents the existing drawing. +In the above example, the blue rectangle represents the new drawing, and the red rectangle represents the existing drawing. ### shadowBlur - ``` + ```html
``` -``` -//xxx.js +```js +// xxx.js export default { onShow() { const el =this.$refs.canvas; @@ -455,15 +455,15 @@ export default { ### shadowColor -``` +```html
``` -``` -//xxx.js +```js +// xxx.js export default { onShow() { const el =this.$refs.canvas; @@ -480,15 +480,15 @@ export default { ### shadowOffsetX -``` +```html
``` -``` -//xxx.js +```js +// xxx.js export default { onShow() { const el =this.$refs.canvas; @@ -507,15 +507,15 @@ export default { ### shadowOffsetY -``` +```html
``` -``` -//xxx.js +```js +// xxx.js export default { onShow() { const el =this.$refs.canvas; @@ -533,15 +533,15 @@ export default { ### imageSmoothingEnabled6+ -``` +```html
``` -``` -//xxx.js +```js +// xxx.js export default { onShow() { const el =this.$refs.canvas; @@ -569,23 +569,24 @@ fillRect(x: number, y: number, width:number, height: number): void Fills a rectangle on the canvas. -- Parameters - | Name | Type | Description | - | ------ | ------ | ------------- | - | x | number | X-coordinate of the upper left corner of the rectangle.| - | y | number | Y-coordinate of the upper left corner of the rectangle.| - | width | number | Width of the rectangle. | - | height | number | Height of the rectangle. | +**Parameters** +| Name | Type | Description | +| ------ | ------ | ------------- | +| x | number | X-coordinate of the upper left corner of the rectangle.| +| y | number | Y-coordinate of the upper left corner of the rectangle.| +| width | number | Width of the rectangle. | +| height | number | Height of the rectangle. | -- Example -``` +**Example** + +```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -604,23 +605,23 @@ clearRect(x: number, y: number, width:number, height: number): void Clears the content in a rectangle on the canvas. -- Parameters - | Name | Type | Description | - | ------ | ------ | ------------- | - | x | number | X-coordinate of the upper left corner of the rectangle.| - | y | number | Y-coordinate of the upper left corner of the rectangle.| - | width | number | Width of the rectangle. | - | height | number | Height of the rectangle. | +**Parameters** +| Name | Type | Description | +| ------ | ------ | ------------- | +| x | number | X-coordinate of the upper left corner of the rectangle.| +| y | number | Y-coordinate of the upper left corner of the rectangle.| +| width | number | Width of the rectangle. | +| height | number | Height of the rectangle. | -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -642,23 +643,23 @@ strokeRect(x: number, y: number, width:number, height: number): void Draws a rectangle stroke on the canvas. -- Parameters - | Name | Type | Description | - | ------ | ------ | ------------ | - | x | number | X-coordinate of the upper left corner of the rectangle stroke.| - | y | number | Y-coordinate of the upper left corner of the rectangle stroke.| - | width | number | Width of the rectangle. | - | height | number | Height of the rectangle. | +**Parameters** +| Name | Type | Description | +| ------ | ------ | ------------ | +| x | number | X-coordinate of the upper left corner of the rectangle stroke.| +| y | number | Y-coordinate of the upper left corner of the rectangle stroke.| +| width | number | Width of the rectangle. | +| height | number | Height of the rectangle. | -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -678,22 +679,22 @@ fillText(text: string, x: number, y: number): void Draws filled text on the canvas. -- Parameters - | Name | Type | Description | - | ---- | ------ | --------------- | - | text | string | Text to draw. | - | x | number | X-coordinate of the lower left corner of the text.| - | y | number | Y-coordinate of the lower left corner of the text.| +**Parameters** +| Name | Type | Description | +| ---- | ------ | --------------- | +| text | string | Text to draw. | +| x | number | X-coordinate of the lower left corner of the text.| +| y | number | Y-coordinate of the lower left corner of the text.| -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -713,22 +714,22 @@ strokeText(text: string, x: number, y: number): void Draws a text stroke on the canvas. -- Parameters - | Name | Type | Description | - | ---- | ------ | --------------- | - | text | string | Text to draw. | - | x | number | X-coordinate of the lower left corner of the text.| - | y | number | Y-coordinate of the lower left corner of the text.| +**Parameters** +| Name | Type | Description | +| ---- | ------ | --------------- | +| text | string | Text to draw. | +| x | number | X-coordinate of the lower left corner of the text.| +| y | number | Y-coordinate of the lower left corner of the text.| -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -748,25 +749,25 @@ measureText(text: string): TextMetrics Returns a **TextMetrics** object used to obtain the width of specified text. -- Parameters - | Name | Type | Description | - | ---- | ------ | ---------- | - | text | string | Text to be measured.| +**Parameters** +| Name | Type | Description | +| ---- | ------ | ---------- | +| text | string | Text to be measured.| -- Return value - | Type | Description | - | ----------- | -------------------------------------- | - | TextMetrics | Object that contains the text width. You can obtain the width by **TextMetrics.width**.| +**Return value** +| Type | Description | +| ----------- | -------------------------------------- | +| TextMetrics | Object that contains the text width. You can obtain the width by **TextMetrics.width**.| -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -788,15 +789,15 @@ stroke(): void Draws a stroke. -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -819,15 +820,15 @@ beginPath(): void Creates a drawing path. -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -851,21 +852,21 @@ moveTo(x: number, y: number): void Moves a drawing path to a target position on the canvas. -- Parameters - | Name | Type | Description | - | ---- | ------ | --------- | - | x | number | X-coordinate of the target position.| - | y | number | Y-coordinate of the target position.| +**Parameters** +| Name | Type | Description | +| ---- | ------ | --------- | +| x | number | X-coordinate of the target position.| +| y | number | Y-coordinate of the target position.| -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -887,21 +888,21 @@ lineTo(x: number, y: number): void Connects the current point to a target position using a straight line. -- Parameters - | Name | Type | Description | - | ---- | ------ | --------- | - | x | number | X-coordinate of the target position.| - | y | number | Y-coordinate of the target position.| +**Parameters** +| Name | Type | Description | +| ---- | ------ | --------- | +| x | number | X-coordinate of the target position.| +| y | number | Y-coordinate of the target position.| -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -923,15 +924,15 @@ closePath(): void Draws a closed path. -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -955,26 +956,26 @@ createPattern(image: Image, repetition: string): Object Creates a pattern for image filling based on a specified source image and repetition mode. -- Parameters - | Name | Type | Description | - | ---------- | ------ | ---------------------------------------- | - | image | Image | Source image. For details, see [Image](../arkui-js/js-components-canvas-image.md).| - | repetition | string | Repetition mode. The value can be **"repeat"**, **"repeat-x"**, **"repeat-y"**, or **"no-repeat"**.| +**Parameters** +| Name | Type | Description | +| ---------- | ------ | ---------------------------------------- | +| image | Image | Source image. For details, see [Image](../arkui-js/js-components-canvas-image.md).| +| repetition | string | Repetition mode. The value can be **"repeat"**, **"repeat-x"**, **"repeat-y"**, or **"no-repeat"**.| -- Return value - | Type | Description | - | ------ | ----------------- | - | Object | Pattern of image filling.| +**Return value** +| Type | Description | +| ------ | ----------------- | +| Object | Pattern of image filling.| -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -997,25 +998,25 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, Draws a cubic bezier curve on the canvas. -- Parameters - | Name | Type | Description | - | ---- | ------ | -------------- | - | cp1x | number | X-coordinate of the first parameter of the bezier curve.| - | cp1y | number | Y-coordinate of the first parameter of the bezier curve.| - | cp2x | number | X-coordinate of the second parameter of the bezier curve.| - | cp2y | number | Y-coordinate of the second parameter of the bezier curve.| - | x | number | X-coordinate of the end point on the bezier curve. | - | y | number | Y-coordinate of the end point on the bezier curve. | - -- Example - ``` +**Parameters** +| Name | Type | Description | +| ---- | ------ | -------------- | +| cp1x | number | X-coordinate of the first parameter of the bezier curve.| +| cp1y | number | Y-coordinate of the first parameter of the bezier curve.| +| cp2x | number | X-coordinate of the second parameter of the bezier curve.| +| cp2y | number | Y-coordinate of the second parameter of the bezier curve.| +| x | number | X-coordinate of the end point on the bezier curve. | +| y | number | Y-coordinate of the end point on the bezier curve. | + +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1037,23 +1038,23 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void Draws a quadratic curve on the canvas. -- Parameters - | Name | Type | Description | - | ---- | ------ | ----------- | - | cpx | number | X-coordinate of the bezier curve parameter.| - | cpy | number | Y-coordinate of the bezier curve parameter.| - | x | number | X-coordinate of the end point on the bezier curve.| - | y | number | Y-coordinate of the end point on the bezier curve.| +**Parameters** +| Name | Type | Description | +| ---- | ------ | ----------- | +| cpx | number | X-coordinate of the bezier curve parameter.| +| cpy | number | Y-coordinate of the bezier curve parameter.| +| x | number | X-coordinate of the end point on the bezier curve.| +| y | number | Y-coordinate of the end point on the bezier curve.| -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1075,25 +1076,25 @@ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, Draws an arc on the canvas. -- Parameters - | Name | Type | Description | - | ------------- | ------- | ---------- | - | x | number | X-coordinate of the center point of the arc.| - | y | number | Y-coordinate of the center point of the arc.| - | radius | number | Radius of the arc. | - | startAngle | number | Start radian of the arc. | - | endAngle | number | End radian of the arc. | - | anticlockwise | boolean | Whether to draw the arc counterclockwise.| - -- Example - ``` +**Parameters** +| Name | Type | Description | +| ------------- | ------- | ---------- | +| x | number | X-coordinate of the center point of the arc.| +| y | number | Y-coordinate of the center point of the arc.| +| radius | number | Radius of the arc. | +| startAngle | number | Start radian of the arc. | +| endAngle | number | End radian of the arc. | +| anticlockwise | boolean | Whether to draw the arc counterclockwise.| + +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1114,31 +1115,31 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void Draws an arc based on the radius and points on the arc. -- Parameters - | Name | Type | Description | - | ------ | ------ | --------------- | - | x1 | number | X-coordinate of the first point on the arc.| - | y1 | number | Y-coordinate of the first point on the arc.| - | x2 | number | X-coordinate of the second point on the arc.| - | y2 | number | Y-coordinate of the second point on the arc.| - | radius | number | Radius of the arc. | - -- Example - ``` +**Parameters** +| Name | Type | Description | +| ------ | ------ | --------------- | +| x1 | number | X-coordinate of the first point on the arc.| +| y1 | number | Y-coordinate of the first point on the arc.| +| x2 | number | X-coordinate of the second point on the arc.| +| y2 | number | Y-coordinate of the second point on the arc.| +| radius | number | Radius of the arc. | + +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { const el =this.$refs.canvas; const ctx = el.getContext('2d'); ctx.moveTo(100, 20); - ctx.arcTo(150, 20, 150, 70, 50); // Create an arc. + ctx.arcTo(150, 20, 150, 70, 50); // Create an arc ctx.stroke(); } } @@ -1152,27 +1153,27 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number Draws an ellipse in the specified rectangular region on the canvas. -- Parameters - | Name | Type | Description | - | ------------- | ------ | ------------------------------------ | - | x | number | X-coordinate of the ellipse center. | - | y | number | Y-coordinate of the ellipse center. | - | radiusX | number | Ellipse radius on the x-axis. | - | radiusY | number | Ellipse radius on the y-axis. | - | rotation | number | Rotation angle of the ellipse. The unit is radian. | - | startAngle | number | Angle of the start point for drawing the ellipse. The unit is radian. | - | endAngle | number | Angle of the end point for drawing the ellipse. The unit is radian. | - | anticlockwise | number | Whether to draw the ellipse counterclockwise. The value **0** means clockwise, and **1** means counterclockwise. This parameter is optional. The default value is **0**.| - -- Example - ``` +**Parameters** +| Name | Type | Description | +| ------------- | ------ | ------------------------------------ | +| x | number | X-coordinate of the ellipse center. | +| y | number | Y-coordinate of the ellipse center. | +| radiusX | number | Ellipse radius on the x-axis. | +| radiusY | number | Ellipse radius on the y-axis. | +| rotation | number | Rotation angle of the ellipse. The unit is radian. | +| startAngle | number | Angle of the start point for drawing the ellipse. The unit is radian. | +| endAngle | number | Angle of the end point for drawing the ellipse. The unit is radian. | +| anticlockwise | number | Whether to draw the ellipse counterclockwise. The value **0** means clockwise, and **1** means counterclockwise. This parameter is optional. The default value is **0**.| + +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1193,29 +1194,29 @@ rect(x: number, y: number, width: number, height: number): void Creates a rectangle on the canvas. -- Parameters - | Name | Type | Description | - | ------ | ------ | ------------- | - | x | number | X-coordinate of the upper left corner of the rectangle.| - | y | number | Y-coordinate of the upper left corner of the rectangle.| - | width | number | Width of the rectangle. | - | height | number | Height of the rectangle. | +**Parameters** +| Name | Type | Description | +| ------ | ------ | ------------- | +| x | number | X-coordinate of the upper left corner of the rectangle.| +| y | number | Y-coordinate of the upper left corner of the rectangle.| +| width | number | Width of the rectangle. | +| height | number | Height of the rectangle. | -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { const el =this.$refs.canvas; const ctx = el.getContext('2d'); - ctx.rect(20, 20, 100, 100); // Create a 100*100 rectangle at (20, 20). + ctx.rect(20, 20, 100, 100); // Create a 100*100 rectangle at (20, 20) ctx.stroke(); // Draw it } } @@ -1229,22 +1230,22 @@ fill(): void Fills the area inside a closed path on the canvas. -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { const el =this.$refs.canvas; const ctx = el.getContext('2d'); - ctx.rect(20, 20, 100, 100); // Create a 100*100 rectangle at (20, 20). - ctx.fill(); // Fill the rectangle using default settings. + ctx.rect(20, 20, 100, 100); // Create a 100*100 rectangle at (20, 20) + ctx.fill(); // Draw it in default setting } } ``` @@ -1257,15 +1258,15 @@ clip(): void Sets the current path to a clipping path. -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1274,7 +1275,7 @@ Sets the current path to a clipping path. ctx.rect(0, 0, 200, 200); ctx.stroke(); ctx.clip(); - // Clip a rectangle and fill it with red paint. + // Draw red rectangle after clip ctx.fillStyle = "rgb(255,0,0)"; ctx.fillRect(0, 0, 150, 150); } @@ -1289,20 +1290,20 @@ rotate(rotate: number): void Rotates a canvas clockwise around its coordinate axes. -- Parameters - | Name | Type | Description | - | ------ | ------ | ---------------------------------------- | - | rotate | number | Clockwise rotation angle. You can use **Math.PI / 180** to convert the angle to a radian.| +**Parameters** +| Name | Type | Description | +| ------ | ------ | ---------------------------------------- | +| rotate | number | Clockwise rotation angle. You can use **Math.PI / 180** to convert the angle to a radian.| -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1322,28 +1323,28 @@ scale(x: number, y: number): void Scales the canvas based on scale factors. -- Parameters - | Name | Type | Description | - | ---- | ------ | ----------- | - | x | number | Horizontal scale factor.| - | y | number | Vertical scale factor.| +**Parameters** +| Name | Type | Description | +| ---- | ------ | ----------- | +| x | number | Horizontal scale factor.| +| y | number | Vertical scale factor.| -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { const el =this.$refs.canvas; const ctx = el.getContext('2d'); ctx.strokeRect(10, 10, 25, 25); - ctx.scale(2, 2);// Scale to 200%. + ctx.scale(2, 2);// Scale to 200% ctx.strokeRect(10, 10, 25, 25); } } @@ -1357,32 +1358,32 @@ transform(scaleX: number, skewX: number, skewY: number, scale: number, translate Defines a transformation matrix. To transform a graph, you only need to set parameters of the matrix. The coordinates of the graph are multiplied by the matrix values to obtain new coordinates of the transformed graph. You can use the matrix to implement multiple transform effects. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> The following formulas calculate coordinates of the transformed graph. **x** and **y** represent coordinates before transformation, and **x'** and **y'** represent coordinates after transformation. +> **NOTE**
+> The following formulas calculate coordinates of the transformed graph. **x** and **y** represent coordinates before transformation, and **x'** and **y'** represent coordinates after transformation. > -> - x' = scaleX \* x + skewY \* y + translateX +> - x' = scaleX \* x + skewY \* y + translateX > -> - y' = skewX \* x + scaleY \* y + translateY - -- Parameters - | Name | Type | Description | - | ---------- | ------ | -------- | - | scaleX | number | X-axis scale.| - | skewX | number | X-axis skew.| - | skewY | number | Y-axis skew.| - | scaleY | number | Y-axis scale.| - | translateX | number | X-axis translation.| - | translateY | number | Y-axis translation.| - -- Example - ``` +> - y' = skewX \* x + scaleY \* y + translateY + +**Parameters** +| Name | Type | Description | +| ---------- | ------ | -------- | +| scaleX | number | X-axis scale.| +| skewX | number | X-axis skew.| +| skewY | number | Y-axis skew.| +| scaleY | number | Y-axis scale.| +| translateX | number | X-axis translation.| +| translateY | number | Y-axis translation.| + +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1408,25 +1409,25 @@ setTransform(scaleX: number, skewX: number, skewY: number, scale: number, transl Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** function. -- Parameters - | Name | Type | Description | - | ---------- | ------ | -------- | - | scaleX | number | X-axis scale.| - | skewX | number | X-axis skew.| - | skewY | number | Y-axis skew.| - | scaleY | number | Y-axis scale.| - | translateX | number | X-axis translation.| - | translateY | number | Y-axis translation.| - -- Example - ``` +**Parameters** +| Name | Type | Description | +| ---------- | ------ | -------- | +| scaleX | number | X-axis scale.| +| skewX | number | X-axis skew.| +| skewY | number | Y-axis skew.| +| scaleY | number | Y-axis scale.| +| translateX | number | X-axis translation.| +| translateY | number | Y-axis translation.| + +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1449,21 +1450,21 @@ translate(x: number, y: number): void Moves the origin of the coordinate system. -- Parameters - | Name | Type | Description | - | ---- | ------ | -------- | - | x | number | X-axis translation.| - | y | number | Y-axis translation.| +**Parameters** +| Name | Type | Description | +| ---- | ------ | -------- | +| x | number | X-axis translation.| +| y | number | Y-axis translation.| -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1484,24 +1485,26 @@ createPath2D(path: Path2D, cmds: string): Path2D Creates a **Path2D** object. -- Parameters - | Name | Type | Description | - | ---- | ------ | -------------- | - | path | Path2D | **Path2D** object. | - | cmds | string | Path description of the SVG image.| +**Parameters** +| Name | Type | Description | +| ---- | ------ | -------------- | +| path | Path2D | **Path2D** object. | +| cmds | string | Path description of the SVG image.| -- Return value - [Path2D object](../arkui-js/js-components-canvas-path2d.md) +**Return value** -- Example - ``` +[Path2D object](../arkui-js/js-components-canvas-path2d.md) + +**Example** + + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1525,32 +1528,32 @@ Creates a **Path2D** object. ### drawImage -drawImage(image: Image, sx: number, sy: number, sWidth: number, sHeight: number, dx: number, dy: number, dWidth: number, dHeight: number):void +drawImage(image: Image | PixelMap, sx: number, sy: number, sWidth: number, sHeight: number, dx: number, dy: number, dWidth: number, dHeight: number):void Draws an image on the canvas. -- Parameters - | Name | Type | Description | - | ------- | ------ | ---------------------------------------- | - | image | Image | Source image. For details, see [Image](../arkui-js/js-components-canvas-image.md).| - | sx | number | X-coordinate of the upper left corner of the rectangle used to crop the source image. | - | sy | number | Y-coordinate of the upper left corner of the rectangle used to crop the source image. | - | sWidth | number | Target width to crop the source image. | - | sHeight | number | Target height to crop the source image. | - | dx | number | X-coordinate of the upper left corner of the drawing area on the canvas. | - | dy | number | Y-coordinate of the upper left corner of the drawing area on the canvas. | - | dWidth | number | Width of the drawing area. | - | dHeight | number | Height of the drawing area. | - -- Example - ``` +**Parameters** +| Name | Type | Description | +| ------- | ------------------------------ | ---------------------------------------- | +| image | Image \| PixelMap9+ | Image resource. For details, see [Image](../arkui-js/js-components-canvas-image.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7).| +| sx | number | X-coordinate of the upper left corner of the rectangle used to crop the source image. | +| sy | number | Y-coordinate of the upper left corner of the rectangle used to crop the source image. | +| sWidth | number | Target width to crop the source image. | +| sHeight | number | Target height to crop the source image. | +| dx | number | X-coordinate of the upper left corner of the drawing area on the canvas. | +| dy | number | Y-coordinate of the upper left corner of the drawing area on the canvas. | +| dWidth | number | Width of the drawing area. | +| dHeight | number | Height of the drawing area. | + +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1571,15 +1574,15 @@ restore(): void Restores the saved drawing context. -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1596,15 +1599,15 @@ save(): void Saves the current drawing context. -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1621,21 +1624,21 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): Object Creates a linear gradient and returns a **CanvasGradient** object. For details, see [CanvasGradient](../arkui-js/js-components-canvas-canvasgradient.md). -- Parameters - | Name | Type | Description | - | ---- | ------ | -------- | - | x0 | number | X-coordinate of the start point.| - | y0 | number | Y-coordinate of the start point.| - | x1 | number | X-coordinate of the end point.| - | y1 | number | Y-coordinate of the end point.| - -- Return value - | Type | Description | - | ------ | ---------------------- | - | Object | Created **CanvasGradient** object.| - -- Example - ``` +**Parameters** +| Name | Type | Description | +| ---- | ------ | -------- | +| x0 | number | X-coordinate of the start point.| +| y0 | number | Y-coordinate of the start point.| +| x1 | number | X-coordinate of the end point.| +| y1 | number | Y-coordinate of the end point.| + +**Return value** +| Type | Description | +| ------ | ---------------------- | +| Object | Created **CanvasGradient** object.| + +**Example** + ```html
@@ -1643,7 +1646,7 @@ Creates a linear gradient and returns a **CanvasGradient** object. For details,
``` - ``` + ```js // xxx.js export default { handleClick() { @@ -1670,23 +1673,23 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, Creates a radial gradient and returns a **CanvasGradient** object. -- Parameters - | Name | Type | Description | - | ---- | ------ | ----------------- | - | x0 | number | X-coordinate of the center of the start circle. | - | y0 | number | Y-coordinate of the center of the start circle. | - | r0 | number | Radius of the start circle, which must be a non-negative finite number.| - | x1 | number | X-coordinate of the center of the end circle. | - | y1 | number | Y-coordinate of the center of the end circle. | - | r1 | number | Radius of the end circle, which must be a non-negative finite number.| - -- Return value - | Type | Description | - | ------ | ---------------------- | - | Object | Created **CanvasGradient** object.| - -- Example - ``` +**Parameters** +| Name | Type | Description | +| ---- | ------ | ----------------- | +| x0 | number | X-coordinate of the center of the start circle. | +| y0 | number | Y-coordinate of the center of the start circle. | +| r0 | number | Radius of the start circle, which must be a non-negative finite number.| +| x1 | number | X-coordinate of the center of the end circle. | +| y1 | number | Y-coordinate of the center of the end circle. | +| r1 | number | Radius of the end circle, which must be a non-negative finite number.| + +**Return value** +| Type | Description | +| ------ | ---------------------- | +| Object | Created **CanvasGradient** object.| + +**Example** + ```html
@@ -1694,7 +1697,7 @@ Creates a radial gradient and returns a **CanvasGradient** object.
``` - ``` + ```js // xxx.js export default { handleClick() { @@ -1721,27 +1724,27 @@ createImageData(width: number, height: number, imageData: Object): Object Creates an **ImageData** object. For details, see [ImageData](../arkui-js/js-components-canvas-imagedata.md). -- Parameters - | Name | Type | Description | - | --------- | ------ | ----------------- | - | width | number | Width of the **ImageData** object. | - | height | number | Height of the **ImageData** object. | - | imagedata | Object | **ImageData** object with the same width and height copied from the original **ImageData** object.| +**Parameters** +| Name | Type | Description | +| --------- | ------ | ----------------- | +| width | number | Width of the **ImageData** object. | +| height | number | Height of the **ImageData** object. | +| imagedata | Object | **ImageData** object with the same width and height copied from the original **ImageData** object.| -- Return value - | Type | Description | - | ------ | ----------------- | - | Object | Created **ImageData** object.| +**Return value** +| Type | Description | +| ------ | ----------------- | +| Object | Created **ImageData** object.| -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1757,30 +1760,30 @@ Creates an **ImageData** object. For details, see [ImageData](../arkui-js/js-com getImageData(sx: number, sy: number, sw: number, sh: number): Object -Creates an **ImageData** object with pixels in the specified area on the canvas. +Obtains the **ImageData** object created with the pixels within the specified area on the canvas. -- Parameters - | Name | Type | Description | - | ---- | ------ | --------------- | - | sx | number | X-coordinate of the upper left corner of the output area.| - | sy | number | Y-coordinate of the upper left corner of the output area.| - | sw | number | Width of the output area. | - | sh | number | Height of the output area. | +**Parameters** +| Name | Type | Description | +| ---- | ------ | --------------- | +| sx | number | X-coordinate of the upper left corner of the output area.| +| sy | number | Y-coordinate of the upper left corner of the output area.| +| sw | number | Width of the output area. | +| sh | number | Height of the output area. | -- Return value - | Type | Description | - | ------ | ----------------------- | - | Object | **ImageData** object that contains pixels in the specified area on the canvas.| +**Return value** +| Type | Description | +| ------ | ----------------------- | +| Object | **ImageData** object that contains pixels in the specified area on the canvas.| -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1797,26 +1800,26 @@ putImageData(imageData: Object, dx: number, dy: number, dirtyX: number, dirtyY: Puts the **ImageData** onto a rectangular area on the canvas. -- Parameters - | Name | Type | Description | - | ----------- | ------ | ----------------------------- | - | imagedata | Object | **ImageData** object with pixels to put onto the canvas. | - | dx | number | X-axis offset of the rectangular area on the canvas. | - | dy | number | Y-axis offset of the rectangular area on the canvas. | - | dirtyX | number | X-axis offset of the upper left corner of the rectangular area relative to that of the source image.| - | dirtyY | number | Y-axis offset of the upper left corner of the rectangular area relative to that of the source image.| - | dirtyWidth | number | Width of the rectangular area to crop the source image. | - | dirtyHeight | number | Height of the rectangular area to crop the source image. | - -- Example - ``` +**Parameters** +| Name | Type | Description | +| ----------- | ------ | ----------------------------- | +| imagedata | Object | **ImageData** object with pixels to put onto the canvas. | +| dx | number | X-axis offset of the rectangular area on the canvas. | +| dy | number | Y-axis offset of the rectangular area on the canvas. | +| dirtyX | number | X-axis offset of the upper left corner of the rectangular area relative to that of the source image.| +| dirtyY | number | Y-axis offset of the upper left corner of the rectangular area relative to that of the source image.| +| dirtyWidth | number | Width of the rectangular area to crop the source image. | +| dirtyHeight | number | Height of the rectangular area to crop the source image. | + +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1836,26 +1839,67 @@ Puts the **ImageData** onto a rectangular area on the canvas. ![en-us_image_0000001214463283](figures/en-us_image_0000001214463283.png) +### getPixelMap9+ + +getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap + +Obtains the **PixelMap** object created with the pixels within the specified area on the canvas. + +**Parameters** + +| Name | Type | Description | +| ---- | ------ | ------------ | +| sx | number | X-coordinate of the upper left corner of the specified area.| +| sy | number | Y-coordinate of the upper left corner of the specified area.| +| sw | number | Width of the specified area. | +| sh | number | Height of the specified area. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------------- | +| [PixelMap](../apis/js-apis-image.md#pixelmap7) | **PixelMap** object that contains pixels in the specified area on the canvas.| + +**Example** + + ```html + +
+ +
+ ``` + + ```js + //xxx.js + export default { + onShow() { + const test = this.$element('canvasId') + const ctx = test.getContext('2d'); + var pixelMap = ctx.getPixelMap(0, 0, 280, 300); + } + } + ``` + ### setLineDash setLineDash(segments: Array): void Sets the dash line style. -- Parameters - | Name | Type | Description | - | -------- | ----- | -------------------- | - | segments | Array | An array describing the interval of alternate line segments and length of spacing.| +**Parameters** +| Name | Type | Description | +| -------- | ----- | -------------------- | +| segments | Array | An array describing the interval of alternate line segments and length of spacing.| -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1876,20 +1920,20 @@ getLineDash(): Array Obtains the dash line style. -- Return value - | Type | Description | - | ----- | ------------------------ | - | Array | An array describing the interval of alternate line segments and length of spacing.| +**Return value** +| Type | Description | +| ----- | ------------------------ | +| Array | An array describing the interval of alternate line segments and length of spacing.| -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { @@ -1906,20 +1950,20 @@ transferFromImageBitmap(bitmap: ImageBitmap): void Displays the specified **ImageBitmap** object. -- Parameters - | Name | Type | Description | - | ------ | ----------- | ------------------ | - | bitmap | ImageBitmap | **ImageBitmap** object to display.| +**Parameters** +| Name | Type | Description | +| ------ | ----------- | ------------------ | +| bitmap | ImageBitmap | **ImageBitmap** object to display.| -- Example - ``` +**Example** + ```html
``` - ``` + ```js //xxx.js export default { onShow() { diff --git a/en/application-dev/reference/arkui-js/js-components-common-events.md b/en/application-dev/reference/arkui-js/js-components-common-events.md index cd470f8eda16f21d44ed970a3d55a7f6e20fa484..28bceb4b82d812406de1fef949c8d6478b47c6e4 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-events.md +++ b/en/application-dev/reference/arkui-js/js-components-common-events.md @@ -1,7 +1,7 @@ # Universal Events -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> Universal events are supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. +> **NOTE**
+> Universal events are supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. ## Event Description @@ -13,47 +13,49 @@ Different from private events, universal events can be bound to most components. -| Name | Parameter | Name | Support Bubbling | -| ------------------------ | ---------- | ---------------------------------------- | -------------- | -| touchstart | TouchEvent | Triggered when the tapping starts.
> **Note**: For details about **TouchEvent**, see Table 2.| Yes5+| -| touchmove | TouchEvent | Triggered when the tapping moves. | Yes5+| -| touchcancel | TouchEvent | Triggered when the tapping is interrupted. | Yes5+| -| touchend | TouchEvent | Triggered when the tapping ends. | Yes5+| -| click | - | Triggered when a component is clicked. | Yes6+| -| doubleclick7+ | - | Triggered when a component is double-clicked. | No
**Note**: Bubbling is supported since API version 9.| -| longpress | - | Triggered when a component is long pressed. | No
**Note**: Bubbling is supported since API version 9.| -| swipe5+ | SwipeEvent | Triggered when a user quickly swipes on a component.
> **Note**: For details about **SwipeEvent**, see Table 6.| No
**Note**: Bubbling is supported since API version 9.| -| attached6+ | - | Triggered after the current component node is mounted to the render tree. | No | -| detached6+ | - | Triggered when the current component node is removed from the render tree. | No | -| pinchstart7+ | PinchEvent | Triggered when a pinch operation is started.
> **Note**: For details about **PinchEvent**, see Table 7.| No | -| pinchupdate7+ | PinchEvent | Triggered when a pinch operation is in progress. | No | -| pinchend7+ | PinchEvent | Triggered when a pinch operation is ended. | No | -| pinchcancel7+ | PinchEvent | Triggered when a pinch operation is interrupted. | No | -| dragstart7+ | DragEvent | Triggered when dragging starts.
> **Note**: For details about **DragEvent**, see Table 8 .| No | -| drag7+ | DragEvent | Triggered when dragging is in progress. | No | -| dragend7+ | DragEvent | Triggered when dragging is ended. | No | -| dragenter7+ | DragEvent | Triggered when the dragged component enters a drop target. | No | -| dragover7+ | DragEvent | Triggered when the dragged component is being dragged over a drop target. | No | -| dragleave7+ | DragEvent | Triggered when the dragged component leaves a drop target. | No | -| drop7+ | DragEvent | Triggered when the dragged component is dropped on a drop target. | No | - - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> Events not listed in the preceding table are non-bubbling events, such as the [change event](../arkui-js/js-components-basic-input.md#events). For details, see the specific component. +| Name | Parameter | Description | Support Bubbling | +| ------------------------ | ---------- | ---------------------------------------- | ---------------------------------------- | +| touchstart | TouchEvent | Triggered when the tapping starts. For details about **TouchEvent**, see Table 2. | Yes5+ | +| touchmove | TouchEvent | Triggered when the tapping moves. | Yes5+ | +| touchcancel | TouchEvent | Triggered when the tapping is interrupted. | Yes5+ | +| touchend | TouchEvent | Triggered when the tapping ends. | Yes5+ | +| click | - | Triggered when a component is clicked. | Yes6+ | +| doubleclick7+ | - | Triggered when a component is double-clicked. | No
Bubbling is supported since API version 9. | +| longpress | - | Triggered when a component is long pressed. | No
Bubbling is supported since API version 9.| +| swipe5+ | SwipeEvent | Triggered when a user quickly swipes on a component.
For details about **SwipeEvent**, see Table 4. | No
Bubbling is supported since API version 9.| +| attached6+ | - | Triggered after the current component node is mounted to the render tree. | No | +| detached6+ | - | Triggered when the current component node is removed from the render tree. | No | +| pinchstart7+ | PinchEvent | Triggered when a pinch operation is started.
For details about **PinchEvent**, see Table 5.| No | +| pinchupdate7+ | PinchEvent | Triggered when a pinch operation is in progress. | No | +| pinchend7+ | PinchEvent | Triggered when a pinch operation is ended. | No | +| pinchcancel7+ | PinchEvent | Triggered when a pinch operation is interrupted. | No | +| dragstart7+ | DragEvent | Triggered when dragging starts.
For details about **DragEvent**, see Table 6. | No | +| drag7+ | DragEvent | Triggered when dragging is in progress. | No | +| dragend7+ | DragEvent | Triggered when dragging is ended. | No | +| dragenter7+ | DragEvent | Triggered when the dragged component enters a drop target. | No | +| dragover7+ | DragEvent | Triggered when the dragged component is being dragged over a drop target. | No | +| dragleave7+ | DragEvent | Triggered when the dragged component leaves a drop target. | No | +| drop7+ | DragEvent | Triggered when the dragged component is dropped on a drop target. | No | + + +> **NOTE**
+> Events not listed in the preceding table do not support bubbling, such as the [change event](../arkui-js/js-components-basic-input.md#events) of the **** component. For details, see the description of the specific component. **Table 1** BaseEvent -| Attribute | Type | Description | -| --------- | ------ | --------------------------- | -| type | string | Event type, such as **click** and **longpress**.| -| timestamp | number | Timestamp when the event is triggered. | +| Attribute | Type | Description | +| --------------------- | -------------------- | --------------------------- | +| type | string | Event type, such as **click** and **longpress**.| +| timestamp | number | Timestamp when the event is triggered. | +| deviceId6+ | number | ID of the device that triggers the event. | +| target6+ | [Target](#target6)| Target object that triggers the event. | **Table 2** TouchEvent (inherited from BaseEvent) | Attribute | Type | Description | | -------------- | ---------------------- | ---------------------------------------- | | touches | Array<TouchInfo> | Attribute set of the touch event, including the information array of the touch points on the screen. | -| changedTouches | Array<TouchInfo> | Attribute set when a touch event occurs, including the information array of changed touch points on the screen. **changedTouches** has the same data format as **touches** and indicates touch point changes, such as from no touch point to newly generated touch points, from some touch points to no touch point, and location changes. For example, when the user's finger leaves the touchscreen, no data exists in the **touches** array, but **changedTouches** will save the generated data.| +| changedTouches | Array<TouchInfo> | Attribute set when a touch event occurs, including the information array of changed touch points on the screen. **changedTouches** has the same data format as **touches** and indicates touch point changes, including changes in the number and location of touch points. For example, when the user's finger leaves the screen, which means that the number of touch points changes from 1 to 0, **changedTouches** has the relevant data generated, but not **touches**.| **Table 3** TouchInfo @@ -70,7 +72,7 @@ Different from private events, universal events can be bound to most components. | Attribute | Type | Description | | --------------------- | ------ | ---------------------------------------- | -| direction | string | Swiping direction. The value can be one of the following:
1. **left**: Swipe from right to left.
2. **right**: Swipe from left to right.
3. **up**: Swipe upwards.
4. **down**: Swipe downwards.| +| direction | string | Swiping direction. The value can be one of the following:
- **left**: Swipe left.
- **right**: Swipe right.
- **up**: Swipe up.
- **down**: Swipe down.| | distance6+ | number | Swiping distance in the swiping direction. | **Table 5** PinchEvent7+ @@ -83,34 +85,33 @@ Different from private events, universal events can be bound to most components. **Table 6** DragEvent7+ (inherited from BaseEvent) -| Attribute | Type | Description | -| --------- | ------ | ---------------- | -| type | string | Event name. | -| globalX | number | Horizontal distance from the upper left corner of the screen, which acts as the origin of coordinates.| -| globalY | number | Vertical distance from the upper left corner of the screen, which acts as the origin of coordinates.| -| timestamp | number | Timestamp. | +| Attribute | Type | Description | +| ------------------------- | -------------------------------- | ---------------- | +| type | string | Event name. | +| globalX | number | Horizontal distance from the upper left corner of the screen, which acts as the origin of coordinates.| +| globalY | number | Vertical distance from the upper left corner of the screen, which acts as the origin of coordinates.| +| timestamp | number | Timestamp. | +| dataTransfer9+ | [DataTransfer](#datatransfer9)| Object for data transfer. | -## Event Object +## Target6+ When a component triggers an event, the event callback receives an event object by default. You can obtain the corresponding information through the event object. -**target object** - | Attribute | Type | Description | | -------------------- | ------ | ---------------------------------------- | | dataSet6+ | Object | Custom attribute set defined through [data-*](../arkui-js/js-components-common-attributes.md).| **Example** -``` - - +```html + +
- +
``` -``` +```js // xxx.js export default { touchstartfunc(msg) { @@ -119,3 +120,147 @@ export default { } } ``` + +## DataTransfer9+ + +Use **dataTransfer** to transfer data during the drag operation, so you can perform operations on the data when the drag operation is complete. + +### setData9+ + +setData(key: string, value: object): boolean + +Sets the data associated with the specified key. If there is no data associated with the key, the data will be appended. If there is already data associated with the key, the data will replace the existing data in the same position. + +**Parameters** + +| Name | Type | Mandatory | Name | +| ----- | ------ | ---- | ------- | +| key | string | Yes | Data key. | +| value | object | Yes | Data to be stored.| + +**Return value** +| Type | Description | +| ------- | ------------------------ | +| boolean | Operation result. The value **true** means that the operation is successful, and **false** means otherwise.| + +**Example** + +```js +// value in setData can be of a primitive type. +dragStart(e) { + var isSetOk = e.dataTransfer.setData('name', 1); +}, +// value in setData can be of the object type. +dragStart(e) { + var person = new Object(); + person.name = "tom"; + person.age = 21; + var isSetOk = e.dataTransfer.setData('person', person); +} +``` +### getData9+ + +getData(key: string): object + +Obtains the data associated with the specified key. If no data is associated with the key, an empty string will be returned. + +**Parameters** + +| Name | Type | Mandatory | Name | +| ---- | ------ | ---- | ----- | +| key | string | Yes | Data key.| + +**Return value** +| Type | Description | +| ------ | ------ | +| object | Obtained data.| + +**Example** + +```js +dragStart(e) { + var person = new Object(); + person.name = "tom"; + person.age = 21; + e.dataTransfer.setData('person', person); +}, +dragEnd(e){ + var person = e.dataTransfer.getData('person'); +}, +``` +### clearData9+ + +clearData(key?: string): boolean + +Deletes data associated with the specified key. If there is no data associated with the key, this API will not have any effect. +If the key is null, all data will be deleted. + +**Parameters** + +| Name | Type | Mandatory | Name | +| ---- | ------ | ---- | ----- | +| key | string | No | Data key.| + +**Return value** +| Type | Description | +| ------- | ------------------------ | +| boolean | Operation result. The value **true** means that the operation is successful, and **false** means otherwise.| + +**Example** + +```js +dragEnd(e) { + var isSuccess = e.dataTransfer.clearData('name'); +} +``` +### setDragImage9+ + +setDragImage(pixelmap: PixelMap, offsetX: number,offsetY: number): boolean + +Sets a custom drag image. + +**Parameters** + +| Name | Type | Mandatory | Name | +| -------- | -------- | ---- | ---------------------------------------- | +| pixelmap | PixelMap | Yes | Image transferred from the frontend. For details, see [PixelMap](../apis/js-apis-image.md#pixelmap7).| +| offsetX | number | Yes | Horizontal offset relative to the image. | +| offsetY | number | Yes | Vertical offset relative to the image. | + +**Return value** +| Type | Description | +| ---- | ------------------------ | +| bool | Operation result. The value **true** means that the operation is successful, and **false** means otherwise.| + +**Example** + +```js +createPixelMap() { + let color = new ArrayBuffer(4*96*96); + var buffer = new Uint8Array(color); + for (var i = 0; i < buffer.length; i++) { + buffer[i] = (i + 1) % 255; + } + let opts = { + alphaType:0, + editable:true, + pixelFormat:4, + scaleMode:1, + size:{height:96,width:96} + } + const promise = image.createPixelMap(color,opts); + promise.then((data)=> { + console.error('-create pixmap has info message:' + JSON.stringify(data)); + this.pixelMap = data; + this.pixelMapReader = data; + }) +}, + +onInit() { + this.createPixelMap +}, + +dragStart(e) { + e.dataTransfer.setDragImage(this.pixelMapReader, 50, 50); +} +``` diff --git a/en/application-dev/reference/arkui-js/js-components-common-transition.md b/en/application-dev/reference/arkui-js/js-components-common-transition.md index 876d80a6f6a21ea5987290ccb8ad9e8cd05151a7..0880c942a984b48f407c8627034654140f4116d3 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-transition.md +++ b/en/application-dev/reference/arkui-js/js-components-common-transition.md @@ -49,7 +49,7 @@ In the example below, where **PageA** jumps to **PageB**, the shared element is - Click on picture to Jump to ths details + Click on picture to Jump to the details
diff --git a/en/application-dev/reference/arkui-js/js-components-media-video.md b/en/application-dev/reference/arkui-js/js-components-media-video.md index 1e2b132c923351e37d92eafeea3bf71ef34d3fb1..b957ee6d968a2a4b038c4d600d7ea6adef966b40 100644 --- a/en/application-dev/reference/arkui-js/js-components-media-video.md +++ b/en/application-dev/reference/arkui-js/js-components-media-video.md @@ -1,240 +1,134 @@ -# video +# video -The **** component provides a video player. ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->- Configure the following information in the **config.json** file: -> ``` -> "configChanges": ["orientation"] -> ``` +> **NOTE**
+> +> - This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. +> +> - Set **configChanges** under **abilities** in the **config.json** file to **orientation**. +> ``` +> "abilities": [ +> { +> "configChanges": ["orientation"], +> ... +> } +> ] +> ``` -## Required Permissions +The **\