提交 d1bebffb 编写于 作者: K king_he 提交者: Gitee

Merge branch 'master' of gitee.com:openharmony/docs into 0628-a

# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="PLATFORM" />
<option name="distributionType" value="LOCAL" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="C:\Program Files\Huawei\DevEco Studio 3.0.0.800\tools\gradle" />
<option name="gradleJvm" value="#JAVA_INTERNAL" />
<option name="resolveModulePerSourceSet" value="false" />
<option name="useQualifiedModuleNames" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/docs.iml" filepath="$PROJECT_DIR$/.idea/docs.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
\ No newline at end of file
...@@ -309,6 +309,8 @@ zh-cn/application-dev/reference/apis/js-apis-worker.md @zengyawen ...@@ -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-xml.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-testRunner.md @HelloCrease 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-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-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.md @ge-yafang
zh-cn/application-dev/quick-start/start-with-ets-low-code.md @ge-yafang zh-cn/application-dev/quick-start/start-with-ets-low-code.md @ge-yafang
......
...@@ -38,12 +38,13 @@ ...@@ -38,12 +38,13 @@
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/--> <!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/-->
<filteritem type="filename" name="en/contribute/license-and-copyright-specifications.md" desc="already checked"/> <filteritem type="filename" name="en/contribute" desc="already checked"/>
</filefilter> </filefilter>
<filefilter name="copyrightPolicyFilter" desc="Filters for copyright header policies"> <filefilter name="copyrightPolicyFilter" desc="Filters for copyright header policies">
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/--> <!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/-->
<filteritem type="filename" name="en/contribute" desc="already checked"/>
</filefilter> </filefilter>
<filefilter name="licenseFileNamePolicyFilter" desc="Filters for LICENSE file policies"> <filefilter name="licenseFileNamePolicyFilter" desc="Filters for LICENSE file policies">
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
...@@ -65,7 +66,7 @@ ...@@ -65,7 +66,7 @@
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/--> <!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/-->
<filteritem type="filename" name="*.jpg|*.png|*.gif|*.pdf" desc="already checked"/> <filteritem type="filename" name="*.jpg|*.png|*.gif|*.pdf|*.xlsm" desc="already checked"/>
</filefilter> </filefilter>
</filefilterlist> </filefilterlist>
......
...@@ -6,6 +6,8 @@ This repository stores device and application development documents provided by ...@@ -6,6 +6,8 @@ This repository stores device and application development documents provided by
## Contents ## Contents
[OpenAtom OpenHarmony](https://www.openharmony.cn/docs?navId=3&navName=OpenHarmony%20Documentation%20Overview)
[Chinese Documentation](zh-cn/readme.md) [Chinese Documentation](zh-cn/readme.md)
[English Documentation](en/readme.md) [English Documentation](en/readme.md)
...@@ -15,7 +17,7 @@ This repository stores device and application development documents provided by ...@@ -15,7 +17,7 @@ This repository stores device and application development documents provided by
### Latest Versions ### Latest Versions
- master: the latest version. - master: the latest version.
- OpenHarmony 3.2 Beta1. [Learn more](en/release-notes/OpenHarmony-v3.2-beta1.md) - 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) - OpenHarmony 3.1 Release. [Learn more](en/release-notes/OpenHarmony-v3.1-release.md)
......
...@@ -12,22 +12,22 @@ OpenHarmony is designed with a layered architecture, which from bottom to top, c ...@@ -12,22 +12,22 @@ OpenHarmony is designed with a layered architecture, which from bottom to top, c
**Kernel layer** **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** **System service layer**
The system service layer provides a complete set of capabilities essential for OpenHarmony to offer services for apps through the framework layer. This layer consists of the following parts: The system service layer provides a complete set of capabilities essential for OpenHarmony to offer services for 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. 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 ...@@ -42,81 +42,78 @@ This layer consists of system apps and third-party apps. Each OpenHarmony app is
## Technical Features<a name="section12212842173518"></a> ## Technical Features<a name="section12212842173518"></a>
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 - Distributed Scheduler
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. 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 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 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.
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. 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.
- 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.
## OS Types<a name="section145241459142416"></a> ## OS Types<a name="section145241459142416"></a>
OpenHarmony supports the following 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<a name="section25831825174419"></a> ## Subsystems<a name="section25831825174419"></a>
You need to understand the following basic concepts related to OpenHarmony: 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). The following table describes the subsystems of OpenHarmony. For details about the readme files of these subsystems, see [https://gitee.com/openharmony/docs/tree/master/en/readme](https://gitee.com/openharmony/docs/tree/master/en/readme).
| Subsystem| Description| Applicable To| | Subsystem| Description| 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<br> 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<br>Standard system |
| DFileSystem | Provides APIs for synchronizing local JS files. | 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 | | 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 | | 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 | | 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 | | 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 ...@@ -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 | | 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 | | 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 | | 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:<br/> - Local app data management for lightweight preference databases and relational databases<br> - 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:<br/>- Local app data management for lightweight preference databases and relational databases<br>- 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 | | 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 | | 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 | | 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 | | 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 | | 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 | | 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 | | 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 | | 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 |
......
...@@ -20,24 +20,21 @@ ...@@ -20,24 +20,21 @@
- Development - Development
- [Ability Development](ability/Readme-EN.md) - [Ability Development](ability/Readme-EN.md)
- [UI Development](ui/Readme-EN.md) - [UI Development](ui/Readme-EN.md)
- Basic Feature Development - [Common Event and Notification](notification/Readme-EN.md)
- [Common Event and Notification](notification/Readme-EN.md) - [Window Manager](windowmanager/Readme-EN.md)
- [Window Manager](windowmanager/Readme-EN.md) - [WebGL](webgl/Readme-EN.md)
- [WebGL](webgl/Readme-EN.md) - [Media](media/Readme-EN.md)
- [Media](media/Readme-EN.md) - [Security](security/Readme-EN.md)
- [Security](security/Readme-EN.md) - [Connectivity](connectivity/Readme-EN.md)
- [Connectivity](connectivity/Readme-EN.md) - [Data Management](database/Readme-EN.md)
- [Data Management](database/Readme-EN.md) - [Telephony](telephony/Readme-EN.md)
- [Telephony](telephony/Readme-EN.md) - [Task Management](task-management/Readme-EN.md)
- [Agent-Powered Scheduled Reminders](background-agent-scheduled-reminder/Readme-EN.md) - [Device Management](device/Readme-EN.md)
- [Background Task Management](background-task-management/Readme-EN.md) - [Device Usage Statistics](device-usage-statistics/Readme-EN.md)
- [Work Scheduler](work-scheduler/Readme-EN.md) - [DFX](dfx/Readme-EN.md)
- [Device Management](device/Readme-EN.md) - [Internationalization](internationalization/Readme-EN.md)
- [Device Usage Statistics](device-usage-statistics/Readme-EN.md) - [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md)
- [DFX](dfx/Readme-EN.md) - [Using Native APIs in Application Projects](napi/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 - Tools
- [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md)
- Hands-On Tutorials - Hands-On Tutorials
...@@ -47,7 +44,7 @@ ...@@ -47,7 +44,7 @@
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- APIs - APIs
- [JS (eTS Included) APIs](reference/apis/Readme-EN.md) - [JS and TS APIs](reference/apis/Readme-EN.md)
- Native APIs - Native APIs
- [Standard Library](reference/native-lib/third_party_libc/musl.md) - [Standard Library](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md) - [Node_API](reference/native-lib/third_party_napi/napi.md)
......
...@@ -2,11 +2,7 @@ ...@@ -2,11 +2,7 @@
The ability assistant enables you to start applications, atomic services, and test cases and debug applications. By using this tool, you can send commands in the hdc shell to perform various system operations, such as starting abilities, forcibly stopping processes, and printing ability information. The ability assistant enables you to start applications, atomic services, and test cases and debug applications. By using this tool, you can send commands in the hdc shell to perform various system operations, such as starting abilities, forcibly stopping processes, and printing ability information.
## Development Guidelines ## Query-related Commands
The ability assistant is pre-installed in the device environment. You can directly invoke the tool using commands.
### Query-related Commands
- **help** - **help**
...@@ -22,7 +18,7 @@ The ability assistant is pre-installed in the device environment. You can direct ...@@ -22,7 +18,7 @@ The ability assistant is pre-installed in the device environment. You can direct
aa help aa help
``` ```
### Ability-related Commands ## Ability-related Commands
- **start** - **start**
...@@ -69,18 +65,18 @@ The ability assistant is pre-installed in the device environment. You can direct ...@@ -69,18 +65,18 @@ The ability assistant is pre-installed in the device environment. You can direct
- **dump** - **dump**
Prints ability-related information. Prints ability related information.
| Name | Level-2 Parameter | Description | | Name | Level-2 Parameter | Description |
| ----------------- | -------------------- | ------------------------------------------------------------ | | ----------------- | -------------------- | ------------------------------------------------------------ |
| -h/--help | - | Prints help information. | | -h/--help | - | Prints help information. |
| -a/--all | - | Prints ability information in all missions. | | -a/--all | - | Prints ability information in all missions. |
| -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| Prints mission stack information.<br>The following values are available for **type**:<br>- NORMAL <br>- DEFAULT_STANDARD<br>- DEFAULT_SINGLE<br>- LAUNCHER | | -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| Prints mission stack information.<br>The following values are available for **type**:<br>NORMAL <br>DEFAULT_STANDARD<br>DEFAULT_SINGLE<br>LAUNCHER |
| -e/--extension | elementName | Prints extended component information. | | -e/--extension | elementName | Prints extended component information. |
| -u/--userId | UserId | Prints stack information of a specified user ID. This parameter must be used together with other parameters.<br>Example commands: aa **dump -a -u 100** and **aa dump -d -u 100**| | -u/--userId | UserId | Prints stack information of a specified user ID. This parameter must be used together with other parameters. Example commands: aa **dump -a -u 100** and **aa dump -d -u 100**.|
| -d/--data | | Prints Data ability information. | | -d/--data | | Prints Data ability information. |
| -i/--ability | AbilityRecord ID | Prints detailed information about a specified ability. | | -i/--ability | AbilityRecord ID | Prints detailed information about a specified ability. |
| -c/--client | | Prints detailed ability information. This parameter must be used together with other parameters.<br>Example commands: **aa dump -a -c** and **aa dump -i 21 -c**| | -c/--client | | Prints detailed ability information. This parameter must be used together with other parameters. Example commands: **aa dump -a -c** and **aa dump -i 21 -c**.|
**Method** **Method**
......
# Ability Framework Overview # Ability Framework Overview
An ability is the abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more **Ability** instances. An ability is the abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances.
The ability framework model has two forms. The ability framework model has two forms.
- FA model, which applies to application development using API 8 and earlier versions. In the FA model, there are Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities. - FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there are Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities.
- Stage model, which is introduced since API 9. In the stage model, there are Ability and ExtensionAbility. The ExtensionAbility is further extended to ServiceExtensionAbility, FormExtensionAbility, DataShareExtensionAbility, and more. - Stage model, which is introduced since API version 9. In the stage model, there are Ability and ExtensionAbility. The ExtensionAbility is further extended to ServiceExtensionAbility, FormExtensionAbility, DataShareExtensionAbility, and more.
The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models. The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models.
| Item | FA Model | Stage Model | | Item | FA Model | Stage Model |
| -------------- | ------------------------------------------------------------ | -------------------------------------------------------- | | -------------- | ------------------------------------------------------------ | -------------------------------------------------------- |
| Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. | | Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. |
| Engine instance | Each ability in a process exclusively uses a JS VM engine instance. | Multiple abilities in a process share one JS VM engine instance. | | Engine instance | Each ability in a process exclusively uses a JS VM engine instance. | Multiple abilities in a process share one JS VM engine instance. |
| Intra-process object sharing| Not supported. | Supported. | | Intra-process object sharing| Not supported | Supported |
| Bundle description file | The **config.json** file is used to describe the HAP and component information. The component must use a fixed file name.| The **module.json** file is used to describe the HAP and component information. The entry file name can be specified.| | Bundle description file | The `config.json` file is used to describe the HAP and component information. Each component must use a fixed file name.| The `module.json` file is used to describe the HAP and component information. The entry file name can be specified.|
| Component | Four types of components are provided: Page ability (used for UI page display), Service ability (used to provide services), Data ability (used for data sharing), and Form ability (used to provide widgets).| Two types of components are provided: Ability (used for UI page display) and Extension (scenario-based service extension). | | Component | Four types of components are provided: Page ability (used for UI page display), Service ability (used to provide services), Data ability (used for data sharing), and Form ability (used to provide widgets).| Two types of components are provided: Ability (used for UI page display) and Extension (scenario-based service extension). |
In addition, the following differences exist in the development process: In addition, the following differences exist in the development process:
...@@ -28,4 +28,7 @@ In addition, the following differences exist in the development process: ...@@ -28,4 +28,7 @@ In addition, the following differences exist in the development process:
![lifecycle](figures/lifecycle.png) ![lifecycle](figures/lifecycle.png)
For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md). For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md).
\ No newline at end of file ## Samples
The following sample is provided to help you better understand how to develop abilities:
- [Intra- and Inter-page Navigation](https://gitee.com/openharmony/codelabs/tree/master/Ability/PageAbility)
...@@ -12,8 +12,8 @@ The APIs provided by the test framework can be used only in the test HAP. They t ...@@ -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: The test framework can be started in either of the following ways:
- Method 1: Run the <idp:inline class="- topic/inline " val="code" displayname="code" id="code779717408187" tempcmdid="code779717408187">aa test</idp:inline> command. - Method 1: Run the `aa test` command.
- Method 2: Use the IDE. - Method 2: Use DevEco Studio.
### Running aa test ### Running aa test
...@@ -37,16 +37,16 @@ aa test -b BundleName -m com.example.myapplicationfaets -s unittest OpenHarmonyT ...@@ -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. | | -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.| | -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 \<key>\<value> | 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.| | -s \<key>\<value> | 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. | | -D | No | Debug mode for starting the tested application.|
| -h | No | Help information. | | -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 ## 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 ## Introduction to AbilityDelegatorRegistry
...@@ -136,6 +136,7 @@ abilityDelegator.startAbility(want, (err, data) => { ...@@ -136,6 +136,7 @@ abilityDelegator.startAbility(want, (err, data) => {
### Running a Shell Command ### Running a Shell Command
**AbilityDelegator** provides APIs to run shell commands in the test environment. **AbilityDelegator** provides APIs to run shell commands in the test environment.
**Example** **Example**
```javascript ```javascript
...@@ -150,6 +151,7 @@ abilityDelegator.executeShellCommand(cmd, (err, data) => { ...@@ -150,6 +151,7 @@ abilityDelegator.executeShellCommand(cmd, (err, data) => {
### Printing Log Information ### 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. **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** **Example**
```javascript ```javascript
...@@ -165,6 +167,7 @@ abilityDelegator.print(msg, (err) => { ...@@ -165,6 +167,7 @@ abilityDelegator.print(msg, (err) => {
### Finishing the Test and Printing Log Information ### 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. **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** **Example**
```javascript ```javascript
......
...@@ -195,7 +195,7 @@ export default class MainAbility extends Ability { ...@@ -195,7 +195,7 @@ export default class MainAbility extends Ability {
### application/FormExtensionContext ### 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 ## Common Incorrect Usage
......
...@@ -3,22 +3,15 @@ ...@@ -3,22 +3,15 @@
## Overall Architecture ## Overall Architecture
The development of an OpenHarmony application is essentially the development of one or more abilities. By scheduling abilities and managing their lifecycle, OpenHarmony implements application scheduling. The development of an OpenHarmony application is essentially the development of one or more abilities. By scheduling abilities and managing their lifecycle, OpenHarmony implements application scheduling.
The Feature Ability (FA) model applies to application development using API 8 and earlier versions. In this model, there are Page, Service, Data, and Form abilities. The Feature Ability (FA) model applies to application development using API version 8 and earlier versions. In this model, there are Page, Service, Data, and Form abilities.
- The Page ability implements the ArkUI and provides the capability of interacting with users. - The Page ability implements the ArkUI and provides the capability of interacting with users.
- The Service ability does not have a UI. It runs in the background and provides custom services for other abilities to invoke. - The Service ability does not have a UI. It runs in the background and provides custom services for other abilities to invoke.
- The Data ability does not have a UI. It also runs in the background and enables other abilities to insert, delete, and query data. - The Data ability does not have a UI. It runs in the background and enables other abilities to insert, delete, and query data.
- The Form ability provides a widget, which is a UI display mode. - The Form ability provides a widget, which is a UI display mode.
## Application Package Structure
**The following figure shows the application package structure.**
![fa-package-info](figures/fa-package-info.png)
For details about the application package structure, see [Description of the Application Package Structure Configuration File](../quick-start/package-structure.md).
## Lifecycle ## Lifecycle
Among all abilities, the Page ability has the most complex lifecycle, because it has a UI and is the interaction entry of applications. Among all abilities, the Page ability has the most complex lifecycle, because it has a UI and acts as a touchpoint for interacting with users.
**The following figure shows the lifecycle of the Page ability.** **The following figure shows the lifecycle of the Page ability.**
![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png) ![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png)
...@@ -30,6 +23,20 @@ Currently, the **app.js** file provides only the **onCreate** and **onDestroy** ...@@ -30,6 +23,20 @@ Currently, the **app.js** file provides only the **onCreate** and **onDestroy**
## Process and Thread Model ## Process and Thread Model
An application exclusively uses an independent process, and an ability exclusively uses an independent thread. An application process is created when an ability is started for the first time, and a thread is created for this ability too. After the application is started, other abilities in the application are started, and a thread is created for every of these started abilities. Each ability is bound to an independent JSRuntime instance. Therefore, abilities are isolated from each other. An application exclusively uses an independent process, and an ability exclusively uses an independent thread. When an ability is started for the first time, an application process as well as a thread for this ability is created. After the application is started, other abilities in the application are started, and a thread is created for every of these started abilities. Each ability is bound to an independent JSRuntime instance. In this way, abilities are isolated from each other.
![fa-threading-model](figures/fa-threading-model.png) ![fa-threading-model](figures/fa-threading-model.png)
## Samples
The following sample is provided to help you better understand how to develop abilities:
- [`DistributeCalc`: Distributed Calculator (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/Preset/DistributeCalc)
- [`DistributeGraffiti`: Distributed Graffiti (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DistributedGraffiti)
- [Remote FA Startup](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteStartFA)
- [Distributed News App](https://gitee.com/openharmony/codelabs/tree/master/Distributed/NewsDemo)
- [Synced Sketchpad (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts)
- [Distributed Authentication (JS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/GameAuthOpenH)
- [Distributed Game Controller (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/HandleGameApplication)
- [Distributed Mail System (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OHMailETS)
- [Distributed Jigsaw Puzzle (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OpenHarmonyPictureGame)
- [Distributed Control (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteControllerETS)
...@@ -6,32 +6,40 @@ Data ability providers can customize data access-related APIs such as data inser ...@@ -6,32 +6,40 @@ Data ability providers can customize data access-related APIs such as data inser
## Available APIs ## Available APIs
**Table 1** Data ability lifecycle callbacks **Table 1** Data ability lifecycle APIs
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|onInitialized|Called during ability initialization to initialize the relational database (RDB).| |onInitialized?(info: AbilityInfo): void|Called during ability initialization to initialize the relational database (RDB).|
|update|Updates data in the database.| |update?(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>): void|Updates data in the database.|
|query|Queries data in the database.| |query?(uri: string, columns: Array\<string>, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<ResultSet>): void|Queries data in the database.|
|delete|Deletes one or multiple data records from the database.| |delete?(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>): void|Deletes one or more 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.| |normalizeUri?(uri: string, callback: AsyncCallback\<string>): 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|Inserts multiple data records into the database.| |batchInsert?(uri: string, valueBuckets: Array\<rdb.ValuesBucket>, callback: AsyncCallback\<number>): void|Inserts multiple data records into the database.|
|denormalizeUri|Converts a normalized URI generated by **normalizeUri** into a denormalized URI.| |denormalizeUri?(uri: string, callback: AsyncCallback\<string>): void|Converts a normalized URI generated by **normalizeUri** into a denormalized URI.|
|insert|Inserts a data record into the database.| |insert?(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback\<number>): void|Inserts a data record into the database.|
|openFile|Opens a file.| |openFile?(uri: string, mode: string, callback: AsyncCallback\<number>): void|Opens a file.|
|getFileTypes|Obtains the MIME type of a file.| |getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback\<Array\<string>>): void|Obtains the MIME type of a file.|
|getType|Obtains the MIME type matching the data specified by the URI.| |getType?(uri: string, callback: AsyncCallback\<string>): void|Obtains the MIME type matching the data specified by the URI.|
|executeBatch|Operates data in the database in batches.| |executeBatch?(ops: Array\<DataAbilityOperation>, callback: AsyncCallback\<Array\<DataAbilityResult>>): void|Operates data in the database in batches.|
|call|A customized API.| |call?(method: string, arg: string, extras: PacMap, callback: AsyncCallback\<PacMap>): void|Calls a custom API.|
## How to Develop ## How to Develop
### Creating a Data Ability ### 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: The following code snippet shows how to create a Data ability:
```javascript ```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 { export default {
onInitialized(abilityInfo) { onInitialized(abilityInfo) {
console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName) console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName)
...@@ -50,7 +58,7 @@ Data ability providers can customize data access-related APIs such as data inser ...@@ -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++) { for (let i = 0;i < valueBuckets.length; i++) {
console.info('DataAbility batch insert i=' + i) console.info('DataAbility batch insert i=' + i)
if (i < valueBuckets.length - 1) { 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) console.info('DataAbility batch insert ret=' + num)
}) })
} else { } else {
...@@ -76,7 +84,7 @@ Data ability providers can customize data access-related APIs such as data inser ...@@ -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 | | JSON Field| Description |
| ------------ | ------------------------------------------------------------ | | ------------ | ------------------------------------------------------------ |
...@@ -89,15 +97,15 @@ Data ability providers can customize data access-related APIs such as data inser ...@@ -89,15 +97,15 @@ Data ability providers can customize data access-related APIs such as data inser
```json ```json
"abilities":[{ "abilities":[{
"srcPath": "DataAbility", "srcPath": "DataAbility",
"name": ".DataAbility", "name": ".DataAbility",
"icon": "$media:icon", "icon": "$media:icon",
"srcLanguage": "ets", "srcLanguage": "ets",
"description": "$string:description_dataability", "description": "$string:description_dataability",
"type": "data", "type": "data",
"visible": true, "visible": true,
"uri": "dataability://ohos.samples.etsdataability.DataAbility" "uri": "dataability://ohos.samples.etsdataability.DataAbility"
}] }]
``` ```
### Accessing a Data ability ### Accessing a Data ability
...@@ -118,6 +126,10 @@ The basic dependency packages include: ...@@ -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). For details about the APIs provided by **DataAbilityHelper**, see [DataAbilityHelper Module](../reference/apis/js-apis-dataAbilityHelper.md).
```js ```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 (/). // 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 urivar = "dataability:///com.ix.DataAbility"
var DAHelper = featureAbility.acquireDataAbilityHelper( var DAHelper = featureAbility.acquireDataAbilityHelper(
urivar urivar
...@@ -137,7 +149,7 @@ The basic dependency packages include: ...@@ -137,7 +149,7 @@ The basic dependency packages include:
urivar, urivar,
valuesBucket, valuesBucket,
(error, data) => { (error, data) => {
expect(typeof(data)).assertEqual("number") console.log("DAHelper insert result: " + data)
} }
); );
``` ```
...@@ -156,7 +168,7 @@ The basic dependency packages include: ...@@ -156,7 +168,7 @@ The basic dependency packages include:
urivar, urivar,
da, da,
(error, data) => { (error, data) => {
expect(typeof(data)).assertEqual("number") console.log("DAHelper delete result: " + data)
} }
); );
``` ```
...@@ -176,7 +188,7 @@ The basic dependency packages include: ...@@ -176,7 +188,7 @@ The basic dependency packages include:
valuesBucket, valuesBucket,
da, da,
(error, data) => { (error, data) => {
expect(typeof(data)).assertEqual("number") console.log("DAHelper update result: " + data)
} }
); );
``` ```
...@@ -197,7 +209,7 @@ The basic dependency packages include: ...@@ -197,7 +209,7 @@ The basic dependency packages include:
valArray, valArray,
da, da,
(error, data) => { (error, data) => {
expect(typeof(data)).assertEqual("object") console.log("DAHelper query result: " + data)
} }
); );
``` ```
...@@ -217,7 +229,7 @@ The basic dependency packages include: ...@@ -217,7 +229,7 @@ The basic dependency packages include:
urivar, urivar,
cars, cars,
(error, data) => { (error, data) => {
expect(typeof(data)).assertEqual("number") console.log("DAHelper batchInsert result: " + data)
} }
); );
``` ```
...@@ -241,12 +253,12 @@ The basic dependency packages include: ...@@ -241,12 +253,12 @@ The basic dependency packages include:
valuesBucket: {"executeBatch" : "value1",}, valuesBucket: {"executeBatch" : "value1",},
predicates: da, predicates: da,
expectedCount:0, expectedCount:0,
PredicatesBackReferences: {}, predicatesBackReferences: null,
interrupted:true, interrupted:true,
} }
], ],
(error, data) => { (error, data) => {
expect(typeof(data)).assertEqual("object") console.log("DAHelper executeBatch result: " + data)
} }
); );
``` ```
...@@ -265,21 +277,15 @@ The basic dependency packages include: ...@@ -265,21 +277,15 @@ The basic dependency packages include:
}, },
predicates: da, predicates: da,
expectedCount:0, expectedCount:0,
PredicatesBackReferences: {}, predicatesBackReferences: null,
interrupted:true, interrupted:true,
} }
] ]
); );
``` ```
## Development Example ## Samples
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:
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)
...@@ -3,20 +3,12 @@ ...@@ -3,20 +3,12 @@
## Widget Overview ## 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 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: Basic concepts:
- Widget provider - 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.
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 Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update.
- 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.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br> > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> 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. > 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 ...@@ -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: 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**. - Develop the lifecycle callbacks in **LifecycleForm**.
- Create a **FormBindingData** object. - Create a **FormBindingData** instance.
- Update a widget through **FormProvider**. - Update a widget through **FormProvider**.
- Develop the widget UI page. - Develop the widget UI page.
...@@ -46,9 +38,9 @@ The table below describes the lifecycle callbacks provided **LifecycleForm**. ...@@ -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.| | 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. | | 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. | | 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. | | 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). 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 ...@@ -81,7 +73,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li
export default { export default {
onCreate(want) { onCreate(want) {
console.log('FormAbility onCreate'); 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 = { let obj = {
"title": "titleOnCreate", "title": "titleOnCreate",
"detail": "detailOnCreate" "detail": "detailOnCreate"
...@@ -94,7 +86,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li ...@@ -94,7 +86,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li
console.log('FormAbility onCastToNormal'); console.log('FormAbility onCastToNormal');
}, },
onUpdate(formId) { 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'); console.log('FormAbility onUpdate');
let obj = { let obj = {
"title": "titleOnUpdate", "title": "titleOnUpdate",
...@@ -124,11 +116,11 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li ...@@ -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 | | Field| Description | Data Type| Default |
| -------- | ------------------------------------------------------------ | -------- | ------------------------ | | -------- | ------------------------------------------------------------ | -------- | ------------------------ |
...@@ -161,12 +153,12 @@ Configure the **config.json** file for the **Form** ability. ...@@ -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.<br>**true**: The widget is the default one.<br>**false**: The widget is not the default one.| Boolean | No | | isDefault | Whether the widget is a default one. Each ability has only one default widget.<br>**true**: The widget is the default one.<br>**false**: The widget is not the default one.| Boolean | No |
| type | Type of the widget. Available values are as follows:<br>**JS**: indicates a JavaScript-programmed widget. | String | No | | type | Type of the widget. Available values are as follows:<br>**JS**: indicates a JavaScript-programmed widget. | String | No |
| colorMode | Color mode of the widget. Available values are as follows:<br>**auto**: The widget adopts the auto-adaptive color mode.<br>**dark**: The widget adopts the dark color mode.<br>**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| | colorMode | Color mode of the widget. Available values are as follows:<br>**auto**: The widget adopts the auto-adaptive color mode.<br>**dark**: The widget adopts the dark color mode.<br>**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:<br>1 * 2: indicates a grid with one row and two columns.<br>2 * 2: indicates a grid with two rows and two columns.<br>2 * 4: indicates a grid with two rows and four columns.<br>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:<br>**1 * 2**: indicates a grid with one row and two columns.<br>**2 * 2**: indicates a grid with two rows and two columns.<br>**2 * 4**: indicates a grid with two rows and four columns.<br>**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 | | 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:<br>**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.<br>**false**: The widget cannot be updated periodically.| Boolean | No | | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:<br>**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.<br>**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**) | | 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.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>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) | | 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 | | 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) | | 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. ...@@ -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. 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 ...@@ -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 formName = want.parameters["ohos.extra.param.key.form_name"];
let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; 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 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); storeFormInfo(formId, formName, tempFlag, want);
let obj = { let obj = {
...@@ -230,26 +223,28 @@ You should override **onDestroy** to delete widget data. ...@@ -230,26 +223,28 @@ You should override **onDestroy** to delete widget data.
```javascript ```javascript
onDestroy(formId) { onDestroy(formId) {
// Delete widget data.
deleteFormInfo(formId);
console.log('FormAbility onDestroy'); 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). 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. 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 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 ### Developing the Widget UI Page
You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. 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**<br> > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI. > Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI.
- HML: - HML:
...@@ -331,10 +326,8 @@ Now you've got a widget shown below. ...@@ -331,10 +326,8 @@ Now you've got a widget shown below.
![fa-form-example](figures/fa-form-example.png) ![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 FA model:
[FormAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility)
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)
...@@ -102,16 +102,16 @@ By default, **singleton** is used. ...@@ -102,16 +102,16 @@ By default, **singleton** is used.
console.info('onStartRemoteAbility begin'); console.info('onStartRemoteAbility begin');
let params; let params;
let wantValue = { let wantValue = {
bundleName: 'ohos.samples.etsDemo', bundleName: 'ohos.samples.etsDemo',
abilityName: 'ohos.samples.etsDemo.RemoteAbility', abilityName: 'ohos.samples.etsDemo.RemoteAbility',
deviceId: getRemoteDeviceId(), deviceId: getRemoteDeviceId(),
parameters: params parameters: params
}; };
console.info('onStartRemoteAbility want=' + JSON.stringify(wantValue)); console.info('onStartRemoteAbility want=' + JSON.stringify(wantValue));
featureAbility.startAbility({ featureAbility.startAbility({
want: wantValue want: wantValue
}).then((data) => { }).then((data) => {
console.info('onStartRemoteAbility finished, ' + JSON.stringify(data)); console.info('onStartRemoteAbility finished, ' + JSON.stringify(data));
}); });
console.info('onStartRemoteAbility end'); console.info('onStartRemoteAbility end');
} }
...@@ -123,17 +123,17 @@ Obtain **deviceId** from **DeviceManager**. The sample code is as follows: ...@@ -123,17 +123,17 @@ Obtain **deviceId** from **DeviceManager**. The sample code is as follows:
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedHardware.deviceManager';
let dmClass; let dmClass;
function getRemoteDeviceId() { function getRemoteDeviceId() {
if (typeof dmClass === 'object' && dmClass != null) { if (typeof dmClass === 'object' && dmClass != null) {
let list = dmClass.getTrustedDeviceListSync(); let list = dmClass.getTrustedDeviceListSync();
if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') {
console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null"); console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null");
return; return;
} }
console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId);
return list[0].deviceId; return list[0].deviceId;
} else { } else {
console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); 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 ...@@ -143,35 +143,34 @@ In the cross-device scenario, the application must also apply for the data synch
import abilityAccessCtrl from "@ohos.abilityAccessCtrl"; import abilityAccessCtrl from "@ohos.abilityAccessCtrl";
import bundle from '@ohos.bundle'; import bundle from '@ohos.bundle';
async function RequestPermission() { async function RequestPermission() {
console.info('RequestPermission begin'); console.info('RequestPermission begin');
let array: Array<string> = ["ohos.permission.DISTRIBUTED_DATASYNC"]; let array: Array<string> = ["ohos.permission.DISTRIBUTED_DATASYNC"];
let bundleFlag = 0; let bundleFlag = 0;
let tokenID = undefined; let tokenID = undefined;
let userID = 100; let userID = 100;
let appInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', bundleFlag, userID); let appInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', bundleFlag, userID);
tokenID = appInfo.accessTokenId; tokenID = appInfo.accessTokenId;
let atManager = abilityAccessCtrl.createAtManager(); let atManager = abilityAccessCtrl.createAtManager();
let requestPermissions: Array<string> = []; let requestPermissions: Array<string> = [];
for (let i = 0;i < array.length; i++) { for (let i = 0;i < array.length; i++) {
let result = await atManager.verifyAccessToken(tokenID, array[i]); let result = await atManager.verifyAccessToken(tokenID, array[i]);
console.info("verifyAccessToken result:" + JSON.stringify(result)); console.info("verifyAccessToken result:" + JSON.stringify(result));
if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { if (result != abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
} else { requestPermissions.push(array[i]);
requestPermissions.push(array[i]); }
} }
} console.info("requestPermissions:" + JSON.stringify(requestPermissions));
console.info("requestPermissions:" + JSON.stringify(requestPermissions)); if (requestPermissions.length == 0 || requestPermissions == []) {
if (requestPermissions.length == 0 || requestPermissions == []) { return;
return; }
} let context = featureAbility.getContext();
let context = featureAbility.getContext(); context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{
context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{ console.info("data:" + JSON.stringify(data));
console.info("data:" + JSON.stringify(data)); console.info("data requestCode:" + data.requestCode);
console.info("data requestCode:" + data.requestCode); console.info("data permissions:" + data.permissions);
console.info("data permissions:" + data.permissions); console.info("data authResults:" + data.authResults);
console.info("data authResults:" + data.authResults); });
}); console.info('RequestPermission end');
console.info('RequestPermission end');
} }
``` ```
......
...@@ -5,22 +5,20 @@ A Service ability is used to run tasks in the background, such as playing music ...@@ -5,22 +5,20 @@ A Service ability is used to run tasks in the background, such as playing music
## Available APIs ## Available APIs
**Table 1** Service ability lifecycle callbacks **Table 1** Service ability lifecycle APIs
|API|Description| |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.| |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|Called every time a Service ability is created on a client. You can calculate calling statistics and perform initialization operations in this callback.| |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|Called when another ability is connected to the Service ability.| |onConnect?(want: Want): rpc.RemoteObject|Called when another ability is connected to the Service ability.|
|onDisconnect|Called when another ability is disconnected from the Service ability.| |onDisconnect?(want: Want): void|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.| |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 ## 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: 1. Override the Service ability-related lifecycle callbacks to implement your own logic for processing interaction requests.
The following code snippet shows how to create a Service ability:
```javascript ```javascript
export default { export default {
...@@ -32,6 +30,7 @@ A Service ability is used to run tasks in the background, such as playing music ...@@ -32,6 +30,7 @@ A Service ability is used to run tasks in the background, such as playing music
}, },
onConnect(want) { onConnect(want) {
console.log('ServiceAbility OnConnect'); console.log('ServiceAbility OnConnect');
return null;
}, },
onDisconnect(want) { onDisconnect(want) {
console.log('ServiceAbility OnDisConnect'); console.log('ServiceAbility OnDisConnect');
...@@ -41,10 +40,10 @@ A Service ability is used to run tasks in the background, such as playing music ...@@ -41,10 +40,10 @@ A Service ability is used to run tasks in the background, such as playing music
}, },
} }
``` ```
2. Register a Service ability. 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 ```javascript
{ {
...@@ -78,12 +77,12 @@ The following code snippet shows how to start a Service ability running on the l ...@@ -78,12 +77,12 @@ The following code snippet shows how to start a Service ability running on the l
```javascript ```javascript
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let promise = await featureAbility.startAbility( let promise = featureAbility.startAbility(
{ {
want: want:
{ {
bundleName: "com.jstest.serviceability", bundleName: "com.jstest.service",
abilityName: "com.jstest.serviceability.MainAbility", abilityName: "com.jstest.service.ServiceAbility",
}, },
} }
); );
...@@ -93,11 +92,26 @@ After the preceding code is executed, the **startAbility()** API is called to st ...@@ -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 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. - 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 ### 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 ...@@ -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()**. 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 1. Using the IDL to automatically generate code
let mRemote;
function onConnectCallback(element, remote){ 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).
console.log('onConnectLocalService onConnectDone element: ' + element);
console.log('onConnectLocalService onConnectDone remote: ' + remote); 2. Writing code in the corresponding file
mRemote = remote;
if (mRemote == null) { 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.
prompt.showToast({
message: "onConnectLocalService not connected yet" The following code snippet shows how to implement the callbacks:
});
return; ```javascript
} import prompt from '@system.prompt'
let option = new rpc.MessageOption();
let data = new rpc.MessageParcel(); let mRemote;
let reply = new rpc.MessageParcel(); function onConnectCallback(element, remote){
data.writeInt(1); console.log('onConnectLocalService onConnectDone element: ' + element);
data.writeInt(99); console.log('onConnectLocalService onConnectDone remote: ' + remote);
mRemote.sendRequest(1, data, reply, option).then((result) => { mRemote = remote;
console.log('sendRequest success'); if (mRemote == null) {
let msg = reply.readInt();
prompt.showToast({ prompt.showToast({
message: "onConnectLocalService connect result: " + msg, message: "onConnectLocalService not connected yet"
duration: 3000 });
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){ function onDisconnectCallback(element){
console.log('ConnectAbility onDisconnect Callback') console.log('ConnectAbility onDisconnect Callback')
} }
function onFailedCallback(code){ function onFailedCallback(code){
console.log('ConnectAbility onFailed Callback') 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 ```javascript
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let connId = featureAbility.connectAbility( let connId = featureAbility.connectAbility(
{ {
bundleName: "com.jstest.serviceability", bundleName: "com.jstest.service",
abilityName: "com.jstest.serviceability.MainAbility", abilityName: "com.jstest.service.ServiceAbility",
}, },
{ {
onConnect: onConnectCallback, onConnect: onConnectCallback,
onDisconnect: onDisconnectCallback, onDisconnect: onDisconnectCallback,
onFailed: onFailedCallback, 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 ```javascript
import rpc from "@ohos.rpc"; import rpc from "@ohos.rpc";
let mMyStub; let mMyStub;
export default { export default {
onStart() { onStart() {
class MyStub extends rpc.RemoteObject{ class MyStub extends rpc.RemoteObject{
constructor(des) { constructor(des) {
if (typeof des === 'string') { if (typeof des === 'string') {
super(des); super(des);
}
return null;
} }
return null; onRemoteRequest(code, data, reply, option) {
} console.log("ServiceAbility onRemoteRequest called");
onRemoteRequest(code, data, reply, option) { if (code === 1) {
console.log("ServiceAbility onRemoteRequest called"); let op1 = data.readInt();
if (code === 1) { let op2 = data.readInt();
let op1 = data.readInt(); console.log("op1 = " + op1 + ", op2 = " + op2);
let op2 = data.readInt(); reply.writeInt(op1 + op2);
console.log("op1 = " + op1 + ", op2 = " + op2); } else {
reply.writeInt(op1 + op2); console.log("ServiceAbility unknown request code");
} else { }
console.log("ServiceAbility unknown request code"); return true;
} }
return true;
} }
} mMyStub = new MyStub("ServiceAbility-test");
mMyStub = new MyStub("ServiceAbility-test"); },
}, onCommand(want, startId) {
onCommand(want, startId) { console.log('ServiceAbility onCommand');
console.log('ServiceAbility onCommand'); },
}, onConnect(want) {
onConnect(want) { console.log('ServiceAbility OnConnect');
console.log('ServiceAbility OnConnect'); return mMyStub;
return mMyStub; },
}, onDisconnect(want) {
onDisconnect(want) { console.log('ServiceAbility OnDisConnect');
console.log('ServiceAbility OnDisConnect'); },
}, onStop() {
onStop() { console.log('ServiceAbility onStop');
console.log('ServiceAbility onStop'); },
}, }
} ```
```
### Connecting to a Remote Service Ability (Applying only to System Applications)
### Connecting to a Remote Service Ability<a name="section126857614019"></a> (Applying only to System Applications) >**NOTE**
>Note: The **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. Therefore, remote Service ability startup applies only to system applications. >
>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. 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: The following code snippet shows how to implement the callbacks:
```ts ```ts
import prompt from '@system.prompt'
let mRemote; let mRemote;
function onConnectCallback(element, remote){ function onConnectCallback(element, remote){
console.log('onConnectRemoteService onConnectDone element: ' + element); console.log('onConnectRemoteService onConnectDone element: ' + element);
...@@ -264,7 +294,10 @@ The **Want** of the target Service ability must contain the remote **deviceId**, ...@@ -264,7 +294,10 @@ The **Want** of the target Service ability must contain the remote **deviceId**,
```ts ```ts
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedHardware.deviceManager';
// For details about the implementation of dmClass, see the implementation in Distributed Demo in Samples.
let dmClass; let dmClass;
function getRemoteDeviceId() { function getRemoteDeviceId() {
if (typeof dmClass === 'object' && dmClass != null) { if (typeof dmClass === 'object' && dmClass != null) {
let list = dmClass.getTrustedDeviceListSync(); let list = dmClass.getTrustedDeviceListSync();
...@@ -327,15 +360,12 @@ async function RequestPermission() { ...@@ -327,15 +360,12 @@ async function RequestPermission() {
let context = featureAbility.getContext(); let context = featureAbility.getContext();
context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{ context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{
console.info("data:" + JSON.stringify(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 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: The following code snippet shows how the Service ability instance returns itself to the calling ability:
...@@ -398,5 +428,5 @@ export default { ...@@ -398,5 +428,5 @@ export default {
## Samples ## Samples
The following samples are provided to help you better understand how to develop a Service ability: 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) - [`ServiceAbility`: Service Ability Creation and Use (eTS, API version 8)](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) - [`DMS`: Distributed Demo (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS)
...@@ -2,19 +2,18 @@ ...@@ -2,19 +2,18 @@
## When to Use ## 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 ## 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 **Table 1** Ability continuation APIs
|API| Description| |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.| | 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 page.| | onCreate(want: Want, param : LaunchParam): void | Called by the target to restore the data and UI page.|
| **enum** OnContinueResult | Enumerates the return values of **onContinue**. The options are as follows: **AGREE** (request accepted), **REJECT** (request denied), and **MISMATCH** (version mismatch).|
...@@ -22,6 +21,8 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -22,6 +21,8 @@ The following table lists the APIs used for ability continuation. For details ab
![continuation_dev](figures/continuation-info.png) ![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 ## How to Develop
### Application Continuation ### Application Continuation
...@@ -31,78 +32,84 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -31,78 +32,84 @@ The following table lists the APIs used for ability continuation. For details ab
- Configure the application to support ability continuation. - 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. 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 ```javascript
"continuable": true "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. Set **launchType** in the **module.json5** file to **standard** to add multi-instance support to the application.
```javascript ```javascript
"launchType": "standard" "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. Declare the **DISTRIBUTED_DATASYNC** permission in the **module.json5** file for the application.
```javascript ```javascript
"requestPermissions": [ "requestPermissions": [
{ {
"name": "ohos.permission.DISTRIBUTED_DATASYNC" "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 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:
requestPermissions = async () => {
let permissions: Array<string> = [ ```javascript
"ohos.permission.DISTRIBUTED_DATASYNC" requestPermissions = async () => {
]; let permissions: Array<string> = [
let needGrantPermission = false "ohos.permission.DISTRIBUTED_DATASYNC"
let accessManger = accessControl.createAtManager() ];
Logger.info("app permission get bundle info") let needGrantPermission = false
let bundleInfo = await bundle.getApplicationInfo(BUNDLE_NAME, 0, 100) let accessManger = accessControl.createAtManager()
Logger.info(`app permission query permission ${bundleInfo.accessTokenId.toString()}`) Logger.info("app permission get bundle info")
for (const permission of permissions) { let bundleInfo = await bundle.getApplicationInfo(BUNDLE_NAME, 0, 100)
Logger.info(`app permission query grant status ${permission}`) Logger.info(`app permission query permission ${bundleInfo.accessTokenId.toString()}`)
try { for (const permission of permissions) {
let grantStatus = await accessManger.verifyAccessToken(bundleInfo.accessTokenId, permission) Logger.info(`app permission query grant status ${permission}`)
if (grantStatus === PERMISSION_REJECT) { try {
needGrantPermission = true let grantStatus = await accessManger.verifyAccessToken(bundleInfo.accessTokenId, permission)
break; if (grantStatus === PERMISSION_REJECT) {
} needGrantPermission = true
} catch (err) { break;
Logger.error(`app permission query grant status error ${permission} ${JSON.stringify(err)}`) }
needGrantPermission = true } catch (err) {
break; Logger.error(`app permission query grant status error ${permission} ${JSON.stringify(err)}`)
} needGrantPermission = true
} break;
if (needGrantPermission) { }
Logger.info("app permission needGrantPermission") }
try { if (needGrantPermission) {
await this.context.requestPermissionsFromUser(permissions) Logger.info("app permission needGrantPermission")
} catch (err) { try {
Logger.error(`app permission ${JSON.stringify(err)}`) await this.context.requestPermissionsFromUser(permissions)
} } catch (err) {
} else { Logger.error(`app permission ${JSON.stringify(err)}`)
Logger.info("app permission already granted") }
} } 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.
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: Modules to import:
...@@ -111,41 +118,38 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -111,41 +118,38 @@ The following table lists the APIs used for ability continuation. For details ab
import AbilityConstant from '@ohos.application.AbilityConstant'; import AbilityConstant from '@ohos.application.AbilityConstant';
``` ```
- To implement ability continuation, you must implement this API and have the value **AGREE** returned. To implement ability continuation, you must implement this API and have the value **AGREE** returned.
Example
- Example
```javascript ```javascript
onContinue(wantParam : {[key: string]: any}) { onContinue(wantParam : {[key: string]: any}) {
Logger.info("onContinue using distributedObject") Logger.info("onContinue using distributedObject")
// Set the user input data into the want parameter. // Set the user input data into want params.
wantParam["input"] = AppStorage.Get<string>('ContinueInput'); wantParam["input"] = AppStorage.Get<string>('ContinueInput');
Logger.info(`onContinue input = ${wantParam["input"]}`); Logger.info(`onContinue input = ${wantParam["input"]}`);
return AbilityConstant.OnContinueResult.AGREE 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 target device determines whether the startup is **LaunchReason.CONTINUATION** based on **launchReason** in **onCreate()**.
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. After data restore is complete, call **restoreWindowStage** to trigger page restoration.
- The target device determines whether the startup is **LaunchReason.CONTINUATION** based on **launchReason** in **onCreate**. Example
- After data restore is complete, call **restoreWindowStage** to trigger page restoration.
* Example
```javascript ```javascript
onCreate(want, launchParam) { onCreate(want, launchParam) {
Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
globalThis.abilityWant = want; globalThis.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { 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<string>('ContinueInput', input) AppStorage.SetOrCreate<string>('ContinueInput', input)
Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`) 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 ...@@ -159,71 +163,68 @@ The following table lists the APIs used for ability continuation. For details ab
### Data Continuation ### Data Continuation
1. Use distributed objects. 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). 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 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**. - 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 ```javascript
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:undefined}); var g_object = distributedObject.createDistributedObject({name:undefined});
export default class MainAbility extends Ability { export default class MainAbility extends Ability {
contentStorage : ContentStorage contentStorage : ContentStorage
sessionId : string; sessionId : string;
onContinue(wantParam : {[key: string]: any}) { onContinue(wantParam : {[key: string]: any}) {
Logger.info("onContinue using distributedObject") Logger.info("onContinue using distributedObject")
this.sessionId = distributedObject.genSessionId(); this.sessionId = distributedObject.genSessionId();
// Set the session ID for the distributed data object. // Set the session ID for the distributed data object.
g_object.setSessionId(this.sessionId); g_object.setSessionId(this.sessionId);
g_object.name = "Amy"; g_object.name = "Amy";
// Set the session ID into the want parameter. // Set the session ID into the want parameter.
wantParam["session"] = this.sessionId; wantParam["session"] = this.sessionId;
return AbilityConstant.OnContinueResult.AGREE 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);
}
}
} }
``` ```
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);
}
}
}
```
# Stage Model Overview # Stage Model Overview
### Design Ideas ## Design Ideas
The stage model is designed to make it easier to develop complex applications in the distributed environment. The stage model is designed to make it easier to develop complex applications in the distributed environment.
...@@ -8,7 +8,7 @@ The following figure shows the design ideas of the stage model. ...@@ -8,7 +8,7 @@ The following figure shows the design ideas of the stage model.
![stagedesign](figures/stagedesign.png) ![stagedesign](figures/stagedesign.png)
The stage model is designed based on the following considerations: The stage model is designed based on the following considerations:
- **Balance between application capabilities and overall system power consumption** - **Balance between application capabilities and overall system power consumption**
...@@ -20,10 +20,10 @@ The stage model is designed based on the following considerations: ...@@ -20,10 +20,10 @@ The stage model is designed based on the following considerations:
- **Support for multiple device types and window forms** - **Support for multiple device types and window forms**
To support multiple device types and facilitate the implementation of different window forms, the component manager and window manager must be decoupled at the architecture layer for easier tailoring. To achieve this goal, the stage model redefines the ability lifecycle and implements unidirectional dependency of the component manager and window manager. To support multiple device types and facilitate the implementation of different window forms, the component manager and window manager must be decoupled at the architecture layer for easier tailoring. To achieve this goal, the stage model redefines the ability lifecycle and implements unidirectional dependency for the component manager and window manager.
### Basic Concepts ## Basic Concepts
The following figure shows the basic concepts in the stage model. The following figure shows the basic concepts in the stage model.
...@@ -33,24 +33,24 @@ The following figure shows the basic concepts in the stage model. ...@@ -33,24 +33,24 @@ The following figure shows the basic concepts in the stage model.
- **Bundle**: an OpenHarmony application identified by **appid**. A bundle can contain multiple HAP files. Each application has a **bundleName**. However, **bundleName** must be used together with **appid** and other information to uniquely identify an application. - **Bundle**: an OpenHarmony application identified by **appid**. A bundle can contain multiple HAP files. Each application has a **bundleName**. However, **bundleName** must be used together with **appid** and other information to uniquely identify an application.
- **AbilityStage**: runtime class of an HAP. It is created when the HAP is loaded to the process for the first time and is visible to developers in the runtime. - **AbilityStage**: runtime class of an HAP. It is created when the HAP is loaded to the process for the first time and is visible to developers in the runtime.
- **Application**: runtime class of a bundle, which is invisible to developers in the runtime. - **Application**: runtime class of a bundle, which is invisible to developers in the runtime.
- **Context**: provides various capabilities that can be invoked by developers during the runtime. The **Ability** and **ExtensionAbility** classes have their own context classes, which inherit the base class **Context**. The base class provides information such as the bundle name, module name, and path. - **Context**: base class that the context classes of **Ability** and **ExtensionAbility** classes inherit. This class provides various capabilities that can be invoked by developers in the runtime, and various information such as the bundle name, module name, and path.
- **Ability**: provides lifecycle callback, holds the **AbilityContext** class, and supports component continuation and collaboration. - **Ability**: class that provides lifecycle callbacks, holds the **AbilityContext** class, and supports component continuation and collaboration.
- **ExtensionAbility**: general name of scenario-based service extension abilities. The system defines multiple scenario-based **ExtensionAbility** classes, each of which has its own **ExtensionContext**. - **ExtensionAbility**: general name of scenario-based service extension abilities. The system defines multiple scenario-based **ExtensionAbility** classes, each of which has its own **ExtensionContext**.
- **WindowStage**: local window manager. - **WindowStage**: local window manager.
- **Window**: basic unit managed by the window manager. It has an ArkUI engine instance. - **Window**: basic unit managed by the window manager. It has an ArkUI engine instance.
- **ArkUI Page**: displays declarative ArkUI. - **ArkUI Page**: ArkUI development framework page.
### Lifecycle ## Lifecycle
The ability and ability stage lifecycles are the most important concepts in the basic process of an application. The comparison between the FA model lifecycle and stage model lifecycle is provided in [Ability Framework Overview](ability-brief.md). This section focuses on the ability lifecycle transition and the scheduling relationships between the ability, ability stage, and window stage. The ability and ability stage lifecycles are the rudiments of the basic process of an application. For details about how these lifecycles differ from those in the FA model, see [Ability Framework Overview](ability-brief.md). This section focuses on the ability lifecycle transition and the scheduling relationships between the ability, ability stage, and window stage.
![stageabilitylifecyclecallback](figures/stageabilitylifecyclecallback.png) ![stageabilitylifecyclecallback](figures/stageabilitylifecyclecallback.png)
To implement multi-device-form tailoring and multi-window scalability, OpenHarmony decouples the component manager from the window manager. The ability lifecycle defined in the stage model includes only the creation, destruction, foreground, and background states. The gain focus and lose focus states that are closely related to UI content are defined in the window stage. This implements weak coupling between the abilities and windows. On the service side, the window manager notifies the component manager of the foreground and background changes, so the component manager only senses the foreground and background changes but not the focus changes. To implement device-specific tailoring and multi-window scalability, OpenHarmony decouples the component manager from the window manager. The ability lifecycle defined in the stage model includes only the creation, destruction, foreground, and background states. The gain focus and lose focus states that are closely related to UI content are defined in the window stage. This implements weak coupling between the abilities and windows. On the service side, the window manager notifies the component manager of the foreground and background changes, so the component manager only senses the foreground and background changes but not the focus changes.
### Ability Instances and Missions ## Ability Instances and Missions
Abilities can be started in any of the following modes: Abilities can be started in any of the following modes:
...@@ -62,11 +62,11 @@ Abilities can be started in any of the following modes: ...@@ -62,11 +62,11 @@ Abilities can be started in any of the following modes:
Each ability instance corresponds to a mission in **Launcher Recent**. Each ability instance corresponds to a mission in **Launcher Recent**.
The mission corresponding to each ability instance has a snapshot of the ability instance. After the ability instance is destroyed, the ability class information and snapshot are retained in the mission until the user deletes the information or the storage space exceeds the upper limit. The mission corresponding to an ability instance has a snapshot of the ability instance. After the ability instance is destroyed, the ability class information and snapshot are retained in the mission until the user deletes the information or the storage space reaches the upper limit.
![AbilityComponentInstanceMission](figures/AbilityComponentInstanceMission.png) ![AbilityComponentInstanceMission](figures/AbilityComponentInstanceMission.png)
### ExtensionAbility Mechanism ## ExtensionAbility Mechanism
Different from the ability used for page display, the extension ability provides a restricted service running environment. It has the following features: Different from the ability used for page display, the extension ability provides a restricted service running environment. It has the following features:
...@@ -82,9 +82,9 @@ The following figure uses the widget scenario as an example. You can inherit fro ...@@ -82,9 +82,9 @@ The following figure uses the widget scenario as an example. You can inherit fro
![ExtensionAbility](figures/ExtensionAbility.png) ![ExtensionAbility](figures/ExtensionAbility.png)
### Process Model ## Process Model
All OpenHarmony applications are designed to meet the single-process model. In the single-process model, an application is not allowed to configure multiple processes, and all processes in the application are created and managed by the system. Each application supports a maximum of three types of processes: All OpenHarmony applications are designed to meet the single-process model. In the single-process model, all processes in the application are created and managed by the system. Each application supports a maximum of three types of processes:
- Main process: runs all ability components, pages, and service logic. - Main process: runs all ability components, pages, and service logic.
......
...@@ -18,11 +18,11 @@ The table below describes the ability call APIs. For details, see [Ability](../r ...@@ -18,11 +18,11 @@ The table below describes the ability call APIs. For details, see [Ability](../r
**Table 1** Ability call APIs **Table 1** Ability call APIs
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|startAbilityByCall(want: Want): Promise<Caller>|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\<Caller>|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.| |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.| |off(method: string): void|Callback invoked when the callee deregisters a method.|
|call(method: string, data: rpc.Sequenceable): Promise<void>|Sends agreed sequenceable data to the callee.| |call(method: string, data: rpc.Sequenceable): Promise\<void>|Sends agreed sequenceable data to the callee.|
|callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessageParcel>|Sends agreed sequenceable data to the callee and returns the agreed sequenceable data.| |callWithResult(method: string, data: rpc.Sequenceable): Promise\<rpc.MessageParcel>|Sends agreed sequenceable data to the callee and returns the agreed sequenceable data.|
|release(): void|Releases the caller interface.| |release(): void|Releases the caller interface.|
|onRelease(callback: OnReleaseCallBack): void|Registers a callback that is invoked when the caller is disconnected.| |onRelease(callback: OnReleaseCallBack): void|Registers a callback that is invoked when the caller is disconnected.|
...@@ -83,7 +83,7 @@ export default class MySequenceable { ...@@ -83,7 +83,7 @@ export default class MySequenceable {
``` ```
4. Implement **Callee.on** and **Callee.off**. 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 ```ts
const TAG: string = '[CalleeAbility]' const TAG: string = '[CalleeAbility]'
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg'
...@@ -148,7 +148,7 @@ async onButtonGetCaller() { ...@@ -148,7 +148,7 @@ async onButtonGetCaller() {
console.error(TAG + 'get caller failed with ' + error) 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 ```ts
let TAG = '[MainAbility] ' let TAG = '[MainAbility] '
var caller = undefined var caller = undefined
...@@ -172,7 +172,7 @@ context.startAbilityByCall({ ...@@ -172,7 +172,7 @@ context.startAbilityByCall({
console.error(TAG + 'get remote caller failed with ' + error) 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 ```ts
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedHardware.deviceManager';
var dmClass; var dmClass;
...@@ -190,7 +190,7 @@ function getRemoteDeviceId() { ...@@ -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 ```ts
let context = this.context let context = this.context
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC'] let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC']
...@@ -215,7 +215,7 @@ async onButtonCall() { ...@@ -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 ```ts
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg'
originMsg: string = '' originMsg: string = ''
......
# Service Extension Ability Development # Service Extension Ability Development
## When to Use ## 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 ## Available APIs
...@@ -19,7 +19,7 @@ You can customize a class that inherits from **ServiceExtensionAbility** and ove ...@@ -19,7 +19,7 @@ You can customize a class that inherits from **ServiceExtensionAbility** and ove
## Constraints ## 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 ## How to Develop
...@@ -82,4 +82,5 @@ The following sample is provided to help you better understand how to develop a ...@@ -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) - [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. This sample shows how to create a Service Extension ability in the **ServiceExtAbility.ts** file in the **ServiceExtensionAbility** directory.
\ No newline at end of file
# WantAgent Development # 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 ## Available APIs
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
| API | Description| | API | Description|
| ---------------------------------------------------------------------------------------------- | ----------- | | ---------------------------------------------------------------------------------------------- | ----------- |
| wantAgent.getWantAgentInfo(info: WantAgentInfo, callback: AsyncCallback\<WantAgent\>) | Creates a **WantAgent** object. This API uses an asynchronous callback to return the result.| | getWantAgentInfo(info: WantAgentInfo, callback: AsyncCallback\<WantAgent\>) | Creates a **WantAgent** object. This API uses an asynchronous callback to return the result.|
| wantAgent.getWantAgent(info: WantAgentInfo): Promise\<WantAgent\>; | Creates a **WantAgent** object. This API uses a promise to return the result.| | getWantAgent(info: WantAgentInfo): Promise\<WantAgent\> | Creates a **WantAgent** object. This API uses a promise to return the result.|
| commonEvent.trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback\<CompleteData\>) | Triggers a **WantAgent**.| | trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback\<CompleteData\>) | Triggers a **WantAgent** object.|
### How to Develop ## How to Develop
1. Import the **WantAgent** module. 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 3. Create a **WantAgentInfo** object for publishing a common event.
private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations.
//wantAgentInfo ```
var wantAgentInfo = { private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations.
wants: [
{ //wantAgentInfo
deviceId: "", var wantAgentInfo = {
bundleName: "com.example.test", wants: [
abilityName: "com.example.test.MainAbility", {
action: "", action: "event_name", // Set the action name.
entities: [], parameters: {}
uri: "", }
parameters: {} ],
} operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
], requestCode: 0,
operationType: OperationType.START_ABILITY, wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
requestCode: 0, }
wantAgentFlags:[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. // Create a WantAgent object.
wantAgent.getWantAgent(wantAgentInfo, (err, wantAgentObj) => { wantAgent.getWantAgent(wantAgentInfo, (err, wantAgentObj) => {
if (err.code) { if (err.code) {
console.error("[WantAgent]getWantAgent err=" + JSON.stringify(err)) console.error("[WantAgent]getWantAgent err=" + JSON.stringify(err))
} else { } else {
console.log("[WantAgent]getWantAgent success") console.log("[WantAgent]getWantAgent success")
this.wantAgentObj = wantAgentObj this.wantAgentObj = wantAgentObj
} }
}) })
``` ```
4. Trigger the **WantAgent**. 5. Trigger the **WantAgent** object.
``` ```
// Trigger the WantAgent. // Trigger the WantAgent object.
var triggerInfo = { var triggerInfo = {
code:0 code:0
} }
wantAgent.trigger(wantAgentObj, triggerInfo, (completeData) => { wantAgent.trigger(wantAgentObj, triggerInfo, (completeData) => {
console.log("[WantAgent]getWantAgent success, completeData: ", + JSON.stringify(completeData)) console.log("[WantAgent]getWantAgent success, completeData: ", + JSON.stringify(completeData))
}) })
``` ```
\ No newline at end of file
...@@ -24,18 +24,21 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O ...@@ -24,18 +24,21 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O
All applications should be developed on top of these frameworks. All applications should be developed on top of these frameworks.
Then, equip yourself for developing the key features, with the following guidelines: Then, equip yourself for developing the key features, with the following guidelines:
- [Common Event and Notification](notification/Readme-EN.md)
- [Window Manager](windowmanager/Readme-EN.md) - [Window Manager](windowmanager/Readme-EN.md)
- [WebGL](webgl/Readme-EN.md) - [WebGL](webgl/Readme-EN.md)
- [Media](media/Readme-EN.md) - [Media](media/Readme-EN.md)
- [Security](security/Readme-EN.md) - [Security](security/Readme-EN.md)
- [Connectivity](connectivity/Readme-EN.md) - [Connectivity](connectivity/Readme-EN.md)
- [Telephony](telephony/Readme-EN.md)
- [Data Management](database/Readme-EN.md) - [Data Management](database/Readme-EN.md)
- [Agent-Powered Scheduled Reminders](background-agent-scheduled-reminder/Readme-EN.md) - [Task Management](task-management/Readme-EN.md)
- [Background Task Management](background-task-management/Readme-EN.md)
- [Device Management](device/Readme-EN.md) - [Device Management](device/Readme-EN.md)
- [Device Usage Statistics](device-usage-statistics/Readme-EN.md) - [Device Usage Statistics](device-usage-statistics/Readme-EN.md)
- [DFX](dfx/Readme-EN.md) - [DFX](dfx/Readme-EN.md)
- [Internationalization](internationalization/Readme-EN.md) - [Internationalization](internationalization/Readme-EN.md)
- [IDL Specifications and User Guide](IDL/idl-guidelines.md)
- [Using Native APIs in Application Projects](napi/Readme-EN.md)
### Tools ### Tools
...@@ -54,7 +57,7 @@ They are organized as follows: ...@@ -54,7 +57,7 @@ They are organized as follows:
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- APIs - APIs
- [JS (eTS Included) APIs](reference/apis/Readme-EN.md) - [JS and TS APIs](reference/apis/Readme-EN.md)
- Native APIs - Native APIs
- [Standard Library](reference/native-lib/third_party_libc/musl.md) - [Standard Library](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md) - [Node_API](reference/native-lib/third_party_napi/napi.md)
......
...@@ -24,18 +24,21 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O ...@@ -24,18 +24,21 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O
All applications should be developed on top of these frameworks. All applications should be developed on top of these frameworks.
Then, equip yourself for developing the key features, with the following guidelines: Then, equip yourself for developing the key features, with the following guidelines:
- [Common Event and Notification](notification/notification-brief.md)
- [Window Manager](windowmanager/window-overview.md) - [Window Manager](windowmanager/window-overview.md)
- [WebGL](webgl/webgl-overview.md) - [WebGL](webgl/webgl-overview.md)
- [Media](media/audio-overview.md) - [Media](media/audio-overview.md)
- [Security](security/userauth-overview.md) - [Security](security/userauth-overview.md)
- [Connectivity](connectivity/ipc-rpc-overview.md) - [Connectivity](connectivity/ipc-rpc-overview.md)
- [Telephony](telephony/telephony-overview.md)
- [Data Management](database/database-mdds-overview.md) - [Data Management](database/database-mdds-overview.md)
- [Agent-Powered Scheduled Reminders](background-agent-scheduled-reminder/background-agent-scheduled-reminder-overview.md) - [Task Management](task-management/background-task-overview.md)
- [Background Task Management](background-task-management/background-task-overview.md)
- [Device](device/usb-overview.md) - [Device](device/usb-overview.md)
- [Device Usage Statistics](device-usage-statistics/device-usage-statistics-overview.md) - [Device Usage Statistics](device-usage-statistics/device-usage-statistics-overview.md)
- [DFX](dfx/hiappevent-overview.md) - [DFX](dfx/hiappevent-overview.md)
- [Internationalization](internationalization/international-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 ### Tools
...@@ -51,6 +54,8 @@ To make you better understand how functions work together and jumpstart your app ...@@ -51,6 +54,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. API references encompass all components and APIs available in OpenHarmony, helping you use and integrate APIs more effectively.
They are organized as follows: They are organized as follows:
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/js-components-common-attributes.md) - [JS and TS APIs](reference/apis/js-apis-DataUriUtils.md)
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/ts-universal-events-click.md) - Native APIs
- [API Reference](reference/apis/js-apis-DataUriUtils.md) - [Standard Library](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md)
# Agent-Powered Scheduled Reminder
- [Agent-Powered Scheduled Reminder Overview](background-agent-scheduled-reminder-overview.md)
- [Agent-Powered Scheduled Reminder Development](background-agent-scheduled-reminder-guide.md)
# Background Task Management
- [Background Task Management Overview](background-task-overview.md)
- [Background Task Management Development](background-task-dev-guide.md)
\ No newline at end of file
...@@ -133,13 +133,13 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat ...@@ -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. // Register the TestAbilityStub instance with the SystemAbilityManager on the same device as the SA.
auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); 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. // Register the TestAbilityStub instance with the SystemAbilityManager on a different device.
auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
ISystemAbilityManager::SAExtraProp saExtra; ISystemAbilityManager::SAExtraProp saExtra;
saExtra.isDistributed = true; // Set a distributed SA. 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. 6. Obtain the SA.
...@@ -149,12 +149,12 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat ...@@ -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. // Obtain the proxy of the SA registered on the local device.
sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(said); sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(saId);
sptr<ITestAbility> testAbility = iface_cast<ITestAbility>(remoteObject); // Use the iface_cast macro to convert the proxy to a specific type. sptr<ITestAbility> testAbility = iface_cast<ITestAbility>(remoteObject); // Use the iface_cast macro to convert the proxy to a specific type.
// Obtain the proxies of the SAs registered with other devices. // Obtain the proxies of the SAs registered with other devices.
sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(sdid, deviceId); // deviceId identifies a device. sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(saId, deviceId); // deviceId identifies a device.
sptr<TestAbilityProxy> proxy(new TestAbilityProxy(remoteObject)); // Construct a proxy. sptr<TestAbilityProxy> proxy(new TestAbilityProxy(remoteObject)); // Construct a proxy.
``` ```
......
...@@ -13,62 +13,107 @@ Call **createDistributedObject()** to create a distributed data object instance. ...@@ -13,62 +13,107 @@ Call **createDistributedObject()** to create a distributed data object instance.
**Table 1** API for creating a distributed data object instance **Table 1** API for creating a distributed data object instance
| Package | API | Description | | Package| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.data.distributedDataObject | createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>-&nbsp;**source**: attributes of the **distributedObject** set.<br>-&nbsp;**DistributedObject**: returns the distributed object created. | | ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>-&nbsp;**source**: attributes of the **distributedObject** set.<br>-&nbsp;**DistributedObject**: returns the distributed object created.|
### Generating a Session ID ### Generating a Session ID
Call **genSessionId()** to generate a session ID randomly. The generated session ID can be used to set the session ID of a distributed data object. Call **genSessionId()** to generate a session ID randomly. The generated session ID can be used to set the session ID of a distributed data object.
**Table 2** API for generating a session ID randomly **Table 2** API for generating a session ID randomly
| Package | API | Description | | Package| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.data.distributedDataObject | genSessionId(): string | Generates a session ID, which can be used as the session ID of a distributed data object. | | ohos.data.distributedDataObject| genSessionId(): string | Generates a session ID, which can be used as the session ID of a distributed data object.|
### Setting a SessionID for Distributed Data Objects ### Setting a SessionID for Distributed Data Objects
Call **setSessionId()** to set a session ID for a distributed data object. The session ID is a unique identifier for one collaboration across devices. The distributed data objects to be synchronized must be associated with the same session ID. Call **setSessionId()** to set a session ID for a distributed data object. The session ID is a unique identifier for one collaboration across devices. The distributed data objects to be synchronized must be associated with the same session ID.
**Table 3** API for setting a session ID **Table 3** API for setting a session ID
| Class | API | Description | | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.<br>**sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty. | | DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.<br>&nbsp;**sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
### Observing Data Changes ### Observing Data Changes
Call **on()** to subscribe to data changes of a distributed data object. When the data changes, a callback will be invoked to return the data changes. You can use **off()** to unsubscribe from the data changes. Call **on()** to subscribe to data changes of a distributed data object. When the data changes, a callback will be invoked to return the data changes. You can use **off()** to unsubscribe from the data changes.
**Table 4** APIs for observing data changes of a distributed data object **Table 4** APIs for observing data changes of a distributed data object
| Class | API | Description | | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| DistributedDataObject | on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Subscribes to data changes. | | DistributedDataObject| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Subscribes to data changes.|
| DistributedDataObject | off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Unsubscribes from data changes. <br>**Callback**: specifies callback used to return changes of the distributed data object. If this parameter is not specified, all callbacks related to data changes will be unregistered. | | DistributedDataObject| off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Unsubscribes from data changes. **Callback**: specifies callback used to return changes of the distributed data object. If this parameter is not specified, all callbacks related to data changes will be unregistered.|
### Observing Online or Offline Status ### Observing Online or Offline Status
Call **on()** to subscribe to status changes of a distributed data object. The status can be online or offline. When the status changes, a callback will be invoked to return the status. You can use **off()** to unsubscribe from the status changes. Call **on()** to subscribe to status changes of a distributed data object. The status can be online or offline. When the status changes, a callback will be invoked to return the status. You can use **off()** to unsubscribe from the status changes.
**Table 5** APIs for observing status changes of a distributed data object **Table 5** APIs for observing status changes of a distributed data object
| Class | API | Description | | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| DistributedDataObject | on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' \ | 'offline' }>): void | Subscribes to the status changes of a distributed data object. | | DistributedDataObject| on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }>): void | Subscribes to the status changes of a distributed data object.|
| DistributedDataObject | off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' \ | 'offline' }>): void | Unsubscribes from status changes of a distributed data object. | | DistributedDataObject| off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }>): void | Unsubscribes from status changes of a distributed data object.|
### Saving a Distributed Data Object and Revoking the Data Saving Operation
Call **save()** to save a distributed data object. When the application is active, the saved data will not be released. When the application exits and restarts, the data saved on the device will be restored.
Call **revokeSave()** to revoke a distributed data object that is no longer required. If the distributed data object is saved on the local device, **revokeSave()** will delete the data from all trusted devices. If the distributed data object is not saved on the local device, **revokeSave()** will delete the data from the local device.
The saved data will be released in the following cases:
- The data is stored for more than 24 hours.
- The application has been uninstalled.
- Data is successfully restored.
**Table 6** APIs for saving a distributed data object and revoking the saving
| Class| API| Description|
| -------- | -------- | -------- |
| DistributedDataObject | save(deviceId: string): Promise&lt;SaveSuccessResponse&gt; | Saves a distributed data object. This API uses a promise to return the result.|
| DistributedDataObject| save(deviceId: string, callback: AsyncCallback&lt;SaveSuccessResponse&gt;): void | Saves a distributed data object. This API uses an asynchronous callback to return the result.|
| DistributedDataObject | revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the data saving operation. This API uses an asynchronous callback to return the result. |
| DistributedDataObject| revokeSave(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation. This API uses a promise to return the result. |
## How to Develop ## How to Develop
The following example shows how to implement a distributed data object synchronization. The following example shows how to implement a distributed data object synchronization.
1. Import the @ohos.data.distributedDataObject module to the development environment. 1. Import the @ohos.data.distributedDataObject module to the development environment.
```js
```js import distributedObject from '@ohos.data.distributedDataObject';
import distributedObject from '@ohos.data.distributedDataObject'
``` ```
2. Request the permission. <br>Add the required permission in the **config.json** file. The sample code is as follows:
```
{
"module": {
"reqPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
}
]
}
}
```
This permission must also be authorized by the user through a dialog box when the application is started for the first time. The sample code is as follows:
```js
import featureAbility from '@ohos.ability.featureAbility';
function grantPermission() {
console.info('grantPermission');
let context = featureAbility.getContext();
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
console.info(`result.requestCode=${result.requestCode}`)
})
console.info('end grantPermission');
}
grantPermission();
```
2. Obtain a distributed data object instance. 3. Obtain a distributed data object instance.
The sample code is as follows:
```js ```js
var local_object = distributedObject.createDistributedObject({name:undefined, age:undefined, isVis:true, var local_object = distributedObject.createDistributedObject({name:undefined, age:undefined, isVis:true,
parent:undefined, list:undefined}); parent:undefined, list:undefined});
...@@ -76,7 +121,9 @@ The following example shows how to implement a distributed data object synchroni ...@@ -76,7 +121,9 @@ The following example shows how to implement a distributed data object synchroni
``` ```
3. Add the synchronization network. The data objects in the synchronization network include the local and remote objects. 4. Add the synchronization network. The data objects in the synchronization network include the local and remote objects.
The sample code is as follows:
```js ```js
// Local object // Local object
...@@ -91,8 +138,10 @@ The following example shows how to implement a distributed data object synchroni ...@@ -91,8 +138,10 @@ The following example shows how to implement a distributed data object synchroni
// After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18. // After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18.
``` ```
4. Observe the data changes of the distributed data object. You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be called to return the data changes. 5. Observe the data changes of the distributed data object. <br>You can subscribe to data changes of the peer object. When the data in the peer object changes, a callback will be called to return the data changes.
The sample code is as follows:
```js ```js
function changeCallback(sessionId, changeData) { function changeCallback(sessionId, changeData) {
console.info("change" + sessionId); console.info("change" + sessionId);
...@@ -103,13 +152,14 @@ The following example shows how to implement a distributed data object synchroni ...@@ -103,13 +152,14 @@ The following example shows how to implement a distributed data object synchroni
}); });
} }
} }
// To refresh the page in changeCallback, correctly bind (this) to the changeCallback. // To refresh the page in changeCallback, correctly bind (this) to the changeCallback.
local_object.on("change", this.changeCallback.bind(this)); local_object.on("change", this.changeCallback.bind(this));
``` ```
5. Modify object attributes. The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types). 6. Modify object attributes. <br>The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types).
The sample code is as follows:
```js ```js
local_object.name = "jack"; local_object.name = "jack";
local_object.age = 19; local_object.age = 19;
...@@ -127,23 +177,23 @@ The following example shows how to implement a distributed data object synchroni ...@@ -127,23 +177,23 @@ The following example shows how to implement a distributed data object synchroni
local_object.parent.mother = "mom"; local_object.parent.mother = "mom";
``` ```
6. Access the distributed data object. Obtain the distributed data object attribute, which is the latest data on the network. 7. Access the distributed data object. <br>Obtain the distributed data object attribute, which is the latest data on the network.
The sample code is as follows:
```js ```js
console.info("name " + local_object["name"]); console.info("name " + local_object["name"]);
``` ```
8. Unsubscribe from data changes. <br>You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered.
7. Unsubscribe from data changes. You can specify the callback to unsubscribe from. If you do not specify the callback, all data change callbacks of the distributed data object will be unsubscribed from. The sample code is as follows:
```js ```js
// Unsubscribe from the specified data change callback. // Unregister the specified data change callback.
local_object.off("change", changeCallback); local_object.off("change", changeCallback);
// Unsubscribe from all data change callbacks. // Unregister all data change callbacks.
local_object.off("change"); local_object.off("change");
``` ```
9. Subscribe to the status (online/offline) changes of the distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline.
8. Subscribe to the status (online/offline) changes of the distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. The sample code is as follows:
```js ```js
function statusCallback(sessionId, networkId, status) { function statusCallback(sessionId, networkId, status) {
this.response += "status changed " + sessionId + " " + status + " " + networkId; this.response += "status changed " + sessionId + " " + status + " " + networkId;
...@@ -152,22 +202,59 @@ The following example shows how to implement a distributed data object synchroni ...@@ -152,22 +202,59 @@ The following example shows how to implement a distributed data object synchroni
local_object.on("status", this.statusCallback); local_object.on("status", this.statusCallback);
``` ```
9. Unsubscribe from the status changes of the distributed data object. You can specify the callback to unsubscribe from. If you do not specify the callback, this API unsubscribes from all callbacks of this distributed data object. 10. Save a distributed data object and revoke the data saving operation.
```js - Callback
// Unsubscribe from the specified status change callback.
local_object.off("status", statusCallback);
// Unsubscribe from all status change callbacks.
local_object.off("status");
```
10. Remove a distributed data object from the synchronization network. Data changes on the local object will not be synchronized to the removed distributed data object.
```js ```js
local_object.setSessionId(""); // Save a distributed data object.
local_object.save("local", (result, data)=>{
console.log("save callback");
console.info("save sessionId " + data.sessionId);
console.info("save version " + data.version);
console.info("save deviceId " + data.deviceId);
});
// Revoke the data saving operation.
local_object.revokeSave((result, data) =>{
console.log("revokeSave callback");
console.info("revokeSave sessionId " + data.sessionId);
});
``` ```
- Promise
## Samples ```js
// Save a distributed data object.
g_object.save("local").then((result)=>{
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, (result)=>{
console.info("save local failed.");
});
// Revoke the data saving operation.
g_object.revokeSave().then((result)=>{
console.info("revokeSave success.");
}, (result)=>{
console.info("revokeSave failed.");
});
```
11. Unsubscribe from the status changes of the distributed data object. <br>You can specify the callback to unregister. If you do not specify the callback, this API unregister all callbacks of this distributed data object.
The sample code is as follows:
```js
// Unregister the specified status change callback.
local_object.off("status", this.statusCallback);
// Unregister all status change callbacks.
local_object.off("status");
```
12. Remove a distributed data object from the synchronization network. Data changes on the local object will not be synchronized to the removed distributed data object.
The sample code is as follows:
```js
local_object.setSessionId("");
```
## Development Example
The following example is provided for you to better understand the development of distributed data objects: The following example is provided for you to better understand the development of distributed data objects:
...@@ -175,4 +262,3 @@ The following example is provided for you to better understand the development o ...@@ -175,4 +262,3 @@ The following example is provided for you to better understand the development o
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. 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.
...@@ -178,7 +178,3 @@ The following uses a single KV store as an example to describe the development p ...@@ -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)
...@@ -12,22 +12,29 @@ Currently you can have access to statistics on the application usage, and notifi ...@@ -12,22 +12,29 @@ Currently you can have access to statistics on the application usage, and notifi
3. Upon start of a new day 3. Upon start of a new day
- **The application usage statistics can include the following**: - **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) Deregister the callback for application group changes.
If **maxNum** is not specified, the default value **1000** will be used.
### Required Permissions ### 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. - 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 **queryCurrentBundleActiveStates**, **queryAppUsagePriorityGroup**, and **isIdleState**, which are third-party APIs. - This permission is not required for calling third-party APIs: **queryCurrentBundleActiveStates**, **queryAppUsagePriorityGroup()**, and **isIdleState**.
# USB Service Development<a name="EN-US_TOPIC_0000001177435986"></a> # USB Service Development
## When to Use<a name="section312612461984"></a> ## 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. 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<a name="section912mcpsimp"></a> ## APIs
The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management. 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 **Table 1** Open USB APIs
<a name="table948mcpsimp"></a> | API | Description |
<table><thead align="left"><tr id="row954mcpsimp"><th class="cellrowborder" valign="top" width="58.589999999999996%" id="mcps1.2.3.1.1"><p id="p956mcpsimp"><a name="p956mcpsimp"></a><a name="p956mcpsimp"></a>API</p> | ------------------------------------------------------------ | ------------------------------------------------------------ |
</th> | 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. |
<th class="cellrowborder" valign="top" width="41.410000000000004%" id="mcps1.2.3.1.2"><p id="p958mcpsimp"><a name="p958mcpsimp"></a><a name="p958mcpsimp"></a>Description</p> | requestRight(deviceName: string): Promise\<boolean> | Requests the temporary permission for a given application to access the USB device. |
</th> | connectDevice(device: USBDevice): Readonly\<USBDevicePipe> | Connects to the USB device based on the device information returned by **getDevices()**. |
</tr> | getDevices(): Array<Readonly\<USBDevice>> | Obtains the USB device list. |
</thead> | setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. |
<tbody><tr id="row960mcpsimp"><td class="cellrowborder" valign="top" width="58.589999999999996%" headers="mcps1.2.3.1.1 "><p id="p763891054416"><a name="p763891054416"></a><a name="p763891054416"></a>hasRight(deviceName: string): boolean</p> | setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. |
</td> | claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface |
<td class="cellrowborder" valign="top" width="41.410000000000004%" headers="mcps1.2.3.1.2 "><p id="p8666818458"><a name="p8666818458"></a><a name="p8666818458"></a>Checks whether the user, for example, the application or system, has the device access permissions. The value <strong id="b106930333555"><a name="b106930333555"></a><a name="b106930333555"></a>true</strong> is returned if the user has the device access permissions; the value <strong id="b72426431937"><a name="b72426431937"></a><a name="b72426431937"></a>false</strong> is returned otherwise.</p> | function bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise\<number> | Performs bulk transfer. |
</td> | closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. |
</tr> | releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. |
<tr id="row965mcpsimp"><td class="cellrowborder" valign="top" width="58.589999999999996%" headers="mcps1.2.3.1.1 "><p id="p1063810103448"><a name="p1063810103448"></a><a name="p1063810103448"></a>requestRight(deviceName: string): Promise&lt;boolean&gt;</p> | getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. |
</td> | getRawDescriptor(pipe: USBDevicePipe): Uint8Array | Obtains the raw USB descriptor. |
<td class="cellrowborder" valign="top" width="41.410000000000004%" headers="mcps1.2.3.1.2 "><p id="p18677811454"><a name="p18677811454"></a><a name="p18677811454"></a>Requests the temporary permission for a given application to access the USB device.</p> | controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise\<number> | Performs control transfer. |
</td>
</tr> ## How to Develop
<tr id="row970mcpsimp"><td class="cellrowborder" valign="top" width="58.589999999999996%" headers="mcps1.2.3.1.1 "><p id="p196381710194415"><a name="p196381710194415"></a><a name="p196381710194415"></a>connectDevice(device: USBDevice): Readonly&lt;USBDevicePipe&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="41.410000000000004%" headers="mcps1.2.3.1.2 "><p id="p467178204510"><a name="p467178204510"></a><a name="p467178204510"></a>Connects to the USB device based on the device information returned by <strong id="b191413527412"><a name="b191413527412"></a><a name="b191413527412"></a>getDevices()</strong>.</p>
</td>
</tr>
<tr id="row975mcpsimp"><td class="cellrowborder" valign="top" width="58.589999999999996%" headers="mcps1.2.3.1.1 "><p id="p8638171010441"><a name="p8638171010441"></a><a name="p8638171010441"></a>getDevices(): Array&lt;Readonly&lt;USBDevice&gt;&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="41.410000000000004%" headers="mcps1.2.3.1.2 "><p id="p176715864514"><a name="p176715864514"></a><a name="p176715864514"></a>Obtains the USB device list.</p>
</td>
</tr>
<tr id="row1551153313610"><td class="cellrowborder" valign="top" width="58.589999999999996%" headers="mcps1.2.3.1.1 "><p id="p156381410184417"><a name="p156381410184417"></a><a name="p156381410184417"></a>setConfiguration(pipe: USBDevicePipe, config: USBConfig): number</p>
</td>
<td class="cellrowborder" valign="top" width="41.410000000000004%" headers="mcps1.2.3.1.2 "><p id="p126812817456"><a name="p126812817456"></a><a name="p126812817456"></a>Sets the USB device configuration.</p>
</td>
</tr>
<tr id="row1393711361263"><td class="cellrowborder" valign="top" width="58.589999999999996%" headers="mcps1.2.3.1.1 "><p id="p1563812109442"><a name="p1563812109442"></a><a name="p1563812109442"></a>setInterface(pipe: USBDevicePipe, iface: USBInterface): number</p>
</td>
<td class="cellrowborder" valign="top" width="41.410000000000004%" headers="mcps1.2.3.1.2 "><p id="p136868164513"><a name="p136868164513"></a><a name="p136868164513"></a>Sets a USB interface.</p>
</td>
</tr>
<tr id="row149651544154717"><td class="cellrowborder" valign="top" width="58.589999999999996%" headers="mcps1.2.3.1.1 "><p id="p991359174910"><a name="p991359174910"></a><a name="p991359174910"></a>claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number</p>
</td>
<td class="cellrowborder" valign="top" width="41.410000000000004%" headers="mcps1.2.3.1.2 "><p id="p20859028134917"><a name="p20859028134917"></a><a name="p20859028134917"></a>Claims a USB interface</p>
</td>
</tr>
<tr id="row115717481477"><td class="cellrowborder" valign="top" width="58.589999999999996%" headers="mcps1.2.3.1.1 "><p id="p17913393493"><a name="p17913393493"></a><a name="p17913393493"></a>function bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise&lt;number&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="41.410000000000004%" headers="mcps1.2.3.1.2 "><p id="p1786016281498"><a name="p1786016281498"></a><a name="p1786016281498"></a>Performs bulk transfer.</p>
</td>
</tr>
<tr id="row1042013527474"><td class="cellrowborder" valign="top" width="58.589999999999996%" headers="mcps1.2.3.1.1 "><p id="p19913596492"><a name="p19913596492"></a><a name="p19913596492"></a>closePipe(pipe: USBDevicePipe): number</p>
</td>
<td class="cellrowborder" valign="top" width="41.410000000000004%" headers="mcps1.2.3.1.2 "><p id="p686013285492"><a name="p686013285492"></a><a name="p686013285492"></a>Closes a USB device pipe.</p>
</td>
</tr>
<tr id="row954011574471"><td class="cellrowborder" valign="top" width="58.589999999999996%" headers="mcps1.2.3.1.1 "><p id="p491315910499"><a name="p491315910499"></a><a name="p491315910499"></a>releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number</p>
</td>
<td class="cellrowborder" valign="top" width="41.410000000000004%" headers="mcps1.2.3.1.2 "><p id="p14860202813493"><a name="p14860202813493"></a><a name="p14860202813493"></a>Releases a USB interface.</p>
</td>
</tr>
<tr id="row1475577184811"><td class="cellrowborder" valign="top" width="58.589999999999996%" headers="mcps1.2.3.1.1 "><p id="p69131096493"><a name="p69131096493"></a><a name="p69131096493"></a>getFileDescriptor(pipe: USBDevicePipe): number</p>
</td>
<td class="cellrowborder" valign="top" width="41.410000000000004%" headers="mcps1.2.3.1.2 "><p id="p16860202864913"><a name="p16860202864913"></a><a name="p16860202864913"></a>Obtains the file descriptor.</p>
</td>
</tr>
<tr id="row074819259481"><td class="cellrowborder" valign="top" width="58.589999999999996%" headers="mcps1.2.3.1.1 "><p id="p891416916496"><a name="p891416916496"></a><a name="p891416916496"></a>getRawDescriptor(pipe: USBDevicePipe): Uint8Array</p>
</td>
<td class="cellrowborder" valign="top" width="41.410000000000004%" headers="mcps1.2.3.1.2 "><p id="p486042804917"><a name="p486042804917"></a><a name="p486042804917"></a>Obtains the raw USB descriptor.</p>
</td>
</tr>
<tr id="row1557362913482"><td class="cellrowborder" valign="top" width="58.589999999999996%" headers="mcps1.2.3.1.1 "><p id="p129141944919"><a name="p129141944919"></a><a name="p129141944919"></a>controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise&lt;number&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="41.410000000000004%" headers="mcps1.2.3.1.2 "><p id="p78605286493"><a name="p78605286493"></a><a name="p78605286493"></a>Performs control transfer.</p>
</td>
</tr>
</tbody>
</table>
## How to Develop<a name="section980mcpsimp"></a>
You can set a USB device as a host to connect to a device for data transfer. The development procedure is as follows: 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 ...@@ -211,6 +152,4 @@ You can set a USB device as a host to connect to a device for data transfer. The
```js ```js
usb.releaseInterface(pipe, interface); usb.releaseInterface(pipe, interface);
usb.closePipe(pipe); usb.closePipe(pipe);
``` ```
\ No newline at end of file
...@@ -8,20 +8,20 @@ You can set different vibration effects as needed, for example, customizing the ...@@ -8,20 +8,20 @@ You can set different vibration effects as needed, for example, customizing the
## Available APIs ## Available APIs
| Module| API| Description| | Module | API | Description |
| -------- | -------- | -------- | | ------------- | ---------------------------------------- | ------------------------------- |
| ohos.vibrator | vibrate(duration:&nbsp;number):&nbsp;Promise&lt;void&gt; | Triggers vibration with the specified duration. This API uses a promise to return the result.| | ohos.vibrator | vibrate(duration:&nbsp;number):&nbsp;Promise&lt;void&gt; | Triggers vibration with the specified duration. This API uses a promise to return the result. |
| ohos.vibrator | vibrate(duration:&nbsp;number,&nbsp;callback?:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | Triggers vibration with the specified duration. This API uses a callback to return the result.| | ohos.vibrator | vibrate(duration:&nbsp;number,&nbsp;callback?:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | Triggers vibration with the specified duration. This API uses a callback to return the result. |
| ohos.vibrator | vibrate(effectId:&nbsp;EffectId):&nbsp;Promise&lt;void&gt; | Triggers vibration with the specified effect. This API uses a promise to return the result.| | ohos.vibrator | vibrate(effectId:&nbsp;EffectId):&nbsp;Promise&lt;void&gt; | Triggers vibration with the specified effect. This API uses a promise to return the result. |
| ohos.vibrator | vibrate(effectId:&nbsp;EffectId,&nbsp;callback?:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | Triggers vibration with the specified effect. This API uses a callback to return the result.| | ohos.vibrator | vibrate(effectId:&nbsp;EffectId,&nbsp;callback?:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | Triggers vibration with the specified effect. This API uses a callback to return the result.|
| ohos.vibrator | stop(stopMode:&nbsp;VibratorStopMode):&nbsp;Promise&lt;void&gt; | Stops vibration. This API uses a promise to return the result.| | ohos.vibrator | stop(stopMode:&nbsp;VibratorStopMode):&nbsp;Promise&lt;void&gt; | Stops vibration. This API uses a promise to return the result. |
| ohos.vibrator | stop(stopMode:&nbsp;VibratorStopMode,&nbsp;callback?:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | Stops vibration. This API uses a callback to return the result.| | ohos.vibrator | stop(stopMode:&nbsp;VibratorStopMode,&nbsp;callback?:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | Stops vibration. This API uses a callback to return the result. |
## How to Develop ## How to Develop
1. Declare the permissions required for controlling vibrators on the hardware device in the `config.json` file. 1. Declare the permissions required for controlling vibrators on the hardware device in the `config.json` file.
``` ```
"reqPermissions": [ "reqPermissions": [
{ {
...@@ -58,7 +58,7 @@ You can set different vibration effects as needed, for example, customizing the ...@@ -58,7 +58,7 @@ You can set different vibration effects as needed, for example, customizing the
``` ```
2. Trigger the device to vibrate. 2. Trigger the device to vibrate.
``` ```
import vibrator from "@ohos.vibrator" import vibrator from "@ohos.vibrator"
vibrator.vibrate(1000).then((error)=>{ vibrator.vibrate(1000).then((error)=>{
...@@ -71,7 +71,7 @@ You can set different vibration effects as needed, for example, customizing the ...@@ -71,7 +71,7 @@ You can set different vibration effects as needed, for example, customizing the
``` ```
3. Stop the vibration. 3. Stop the vibration.
``` ```
import vibrator from "@ohos.vibrator" import vibrator from "@ohos.vibrator"
vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error)=>{ vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error)=>{
......
...@@ -15,7 +15,7 @@ JS application event logging APIs are provided by the **hiAppEvent** module. ...@@ -15,7 +15,7 @@ JS application event logging APIs are provided by the **hiAppEvent** module.
| write(string eventName, EventType type, object keyValues, AsyncCallback\<void> 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, AsyncCallback\<void> 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\<void> | Promise\<void> | Logs application events in asynchronous mode. This method uses a promise to return the result. | | write(string eventName, EventType type, object keyValues): Promise\<void> | Promise\<void> | 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** **APIs for Event Logging Configuration**
...@@ -23,6 +23,24 @@ When an asynchronous callback is used, the return value can be processed directl ...@@ -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.<br>The value **true** indicates that the operation is successful, and value **false** indicates the opposite. | | configure(ConfigOption config) | boolean | Sets the configuration options for application event logging.<br>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.<br/>The event name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore (\_).<br/>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.<br/>The event type must be a number.<br/>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.<br/>The key name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore (\_).<br/>The key name does not start with a digit or underscore (\_).<br/>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:<br/>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.<br/>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 ## How to Develop
In this example, an application event is logged after the application startup execution page is loaded. In this example, an application event is logged after the application startup execution page is loaded.
......
...@@ -7,20 +7,3 @@ HiAppEvent provides event logging APIs for applications to log the fault, statis ...@@ -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. 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. **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.<br/>The event name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore (\_).<br/>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.<br/>The event type must be a number.<br/>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.<br/>The key name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore (\_).<br/>The key name does not start with a digit or underscore (\_).<br/>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:<br/>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.<br/>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
# Audio Capture Development # Audio Capture Development
--- ## When to Use
## ***Note***:
1. This document applies to JavaScript. You can use the APIs provided by **AudioCapturer** to record raw audio files.
---
## **Summary** ### State Check
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. 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.
## **AudioCapturer Framework** For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md).
The AudioCapturer interface is one of the most important components of the audio framework.
### **Audio Capturing:** **Figure 1** Audio capturer state
The AudioCapturer framework provides APIs for capturing raw audio files.
![](figures/audio-capturer-state.png)
## **Usage**
Here's an example of how to use AudioCapturer to capture a raw audio file. ## How to Develop
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. 1. Use **createAudioCapturer()** to create an **AudioCapturer** instance.
```
var audioStreamInfo = { 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.
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) Subscribe to audio capturer state change events using the **on('stateChange')** API. ```js
If an application wants to take some action based on the state updates in capturer, the application can subscribe to the state change event. var audioStreamInfo = {
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. 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) => { audioCapturer.on('stateChange',(state) => {
console.info('AudioCapturerLog: Changed State to : ' + state) console.info('AudioCapturerLog: Changed State to : ' + state)
switch (state) { switch (state) {
case audio.AudioState.STATE_PREPARED: case audio.AudioState.STATE_PREPARED:
console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------');
console.info('Audio State is : Prepared'); console.info('Audio State is : Prepared');
break; break;
case audio.AudioState.STATE_RUNNING: case audio.AudioState.STATE_RUNNING:
console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------');
console.info('Audio State is : Running'); console.info('Audio State is : Running');
break; break;
case audio.AudioState.STATE_STOPPED: case audio.AudioState.STATE_STOPPED:
console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------');
console.info('Audio State is : stopped'); console.info('Audio State is : stopped');
break; break;
case audio.AudioState.STATE_RELEASED: case audio.AudioState.STATE_RELEASED:
console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------');
console.info('Audio State is : released'); console.info('Audio State is : released');
break; break;
default: default:
console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------');
console.info('Audio State is : invalid'); console.info('Audio State is : invalid');
break; break;
} }
}); });
``` ```
3. Call the **start()** function on the AudioCapturer instance to start/resume the recording task.\ 3. Use **start()** to start audio recording.
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');
}
``` 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 ```js
until the application wants to stop the recording. The following example shows how to write recorded data into a file. var bufferSize = await audioCapturer.getBufferSize();
console.info('AudioRecLog: buffer size: ' + bufferSize);
``` ```
import fileio from '@ohos.fileio';
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.
const path = '/data/data/.pulse_dir/capture_js.wav';
let fd = fileio.openSync(path, 0o102, 0o777); The following example shows how to write recorded data into a file.
if (fd !== null) {
console.info('AudioRecLog: file fd created'); ```js
} import fileio from '@ohos.fileio';
else{
console.info('AudioRecLog: file fd create : FAILED'); const path = '/data/data/.pulse_dir/capture_js.wav';
return; let fd = fileio.openSync(path, 0o102, 0o777);
} if (fd !== null) {
console.info('AudioRecLog: file fd created');
fd = fileio.openSync(path, 0o2002, 0o666); }
if (fd !== null) { else{
console.info('AudioRecLog: file fd opened in append mode'); console.info('AudioRecLog: file fd create : FAILED');
} return;
}
var numBuffersToCapture = 150;
while (numBuffersToCapture) { fd = fileio.openSync(path, 0o2002, 0o666);
var buffer = await audioCapturer.read(bufferSize, true); if (fd !== null) {
if (typeof(buffer) == undefined) { console.info('AudioRecLog: file fd opened in append mode');
console.info('read buffer failed'); }
} else {
var number = fileio.writeSync(fd, buffer); var numBuffersToCapture = 150;
console.info('AudioRecLog: data written: ' + number); while (numBuffersToCapture) {
} var buffer = await audioCapturer.read(bufferSize, true);
if (typeof(buffer) == undefined) {
numBuffersToCapture--; console.info('read buffer failed');
} } else {
``` var number = fileio.writeSync(fd, buffer);
6. Once the recording is complete, call the **stop()** API on the AudioCapturer instance to stop the recording. console.info('AudioRecLog: data written: ' + number);
``` }
await audioCapturer.stop();
if (audioCapturer.state == audio.AudioState.STATE_STOPPED) { numBuffersToCapture--;
console.info('AudioRecLog: Capturer stopped'); }
} else {
console.info('AudioRecLog: Capturer stop failed');
}
``` ```
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(); await audioCapturer.stop();
if (audioCapturer.state == audio.AudioState.STATE_RELEASED) { if (audioCapturer.state == audio.AudioState.STATE_STOPPED) {
console.info('AudioRecLog: Capturer released'); console.info('AudioRecLog: Capturer stopped');
} else { } else {
console.info('AudioRecLog: Capturer release failed'); console.info('AudioRecLog: Capturer stop failed');
} }
``` ```
## **Importance of State Check** 7. After the task is complete, call **release()** to release related resources.
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.
## **Other APIs** ```js
See [AudioCapturer in the Audio API](../reference/apis/js-apis-audio.md) for more useful APIs like **getAudioTime**, **getCapturerInfo** and **getStreamInfo**. await audioCapturer.release();
if (audioCapturer.state == audio.AudioState.STATE_RELEASED) {
console.info('AudioRecLog: Capturer released');
} else {
console.info('AudioRecLog: Capturer release failed');
}
```
# Audio Overview<a name="EN-US_TOPIC_0000001147055469"></a> # Audio Overview
You can use APIs provided by the audio module to implement audio-related features, including audio playback and volume management. You can use APIs provided by the audio module to implement audio-related features, including audio playback and volume management.
>![](../public_sys-resources/icon-note.gif) **NOTE** ## Basic Concepts
>Due to permission issues, the above features are temporarily unavailable for the standard system.
## Basic Concepts<a name="section296512102281"></a> - **Sampling**
Sampling is a process to obtain discrete-time signals by extracting samples from analog signals in a continuous time domain at a specific interval.
- **Sampling** - **Sampling rate**
Sampling rate is the number of samples extracted from a continuous signal per second to form a discrete signal. It is measured in Hz. Generally, human hearing range is from 20 Hz to 20 kHz. Common audio sampling rates include 8 kHz, 11.025 kHz, 22.05 kHz, 16 kHz, 37.8 kHz, 44.1 kHz, 48 kHz, 96 kHz, and 192 kHz.
Sampling is a process to obtain discrete-time signals by extracting samples from analog signals in a continuous time domain at a specific interval. - **Channel**
Channels refer to different spatial positions where independent audio signals are recorded or played. The number of channels is the number of audio sources used during audio recording, or the number of speakers used for audio playback.
- **Sampling rate**
Sampling rate is the number of samples extracted from a continuous signal per second to form a discrete signal. It is measured in Hz. Generally, human hearing range is from 20 Hz to 20 kHz. Common audio sampling rates include 8 kHz, 11.025 kHz, 22.05 kHz, 16 kHz, 37.8 kHz, 44.1 kHz, 48 kHz, 96 kHz, and 192 kHz.
- **Channel**
Channels refer to different spatial positions where independent audio signals are recorded or played. The number of channels is the number of audio sources used during audio recording, or the number of speakers used for audio playback.
- **Audio frame**
Audio data is in stream form. For the convenience of audio algorithm processing and transmission, it is generally agreed that a data amount in a unit of 2.5 to 60 milliseconds is one audio frame. This unit is called sampling time, and its length is specific to codecs and the application requirements.
- **PCM**
Pulse code modulation \(PCM\) is a method used to digitally represent sampled analog signals. It converts continuous-time analog signals into discrete-time digital signal samples.
- **Audio frame**
Audio data is in stream form. For the convenience of audio algorithm processing and transmission, it is generally agreed that a data amount in a unit of 2.5 to 60 milliseconds is one audio frame. This unit is called sampling time, and its length is specific to codecs and the application requirements.
- **PCM**<br>
Pulse code modulation (PCM) is a method used to digitally represent sampled analog signals. It converts continuous-time analog signals into discrete-time digital signal samples.
...@@ -256,7 +256,8 @@ export class AudioDemo { ...@@ -256,7 +256,8 @@ export class AudioDemo {
The following samples are provided to help you better understand how to develop audio playback: The following samples are provided to help you better understand how to develop audio playback:
- [<idp:inline class="- topic/inline " val="code" displayname="code" id="code04927441464" tempcmdid="code04927441464">JsDistributedMusicPlayer</idp:inline>: Distributed Music Player (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/ability/JsDistributedMusicPlayer) - [`JsDistributedMusicPlayer`: Distributed Music Player (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/ability/JsDistributedMusicPlayer)
- [<idp:inline class="- topic/inline " val="code" displayname="code" id="code4276559568" tempcmdid="code4276559568">JsAudioPlayer</idp:inline>: Audio Playback and Management (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer) - [`JsAudioPlayer`: Audio Playback and Management (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer)
- [<idp:inline class="- topic/inline " val="code" displayname="code" id="code246413101579" tempcmdid="code246413101579">eTsAudioPlayer</idp:inline>: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets) - [`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) - [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
...@@ -190,7 +190,8 @@ export class AudioRecorderDemo { ...@@ -190,7 +190,8 @@ export class AudioRecorderDemo {
The following samples are provided to help you better understand how to develop audio recording: The following samples are provided to help you better understand how to develop audio recording:
- [<idp:inline class="- topic/inline " val="code" displayname="code" id="code15884933169" tempcmdid="code15884933169">Recorder</idp:inline>: Recorder (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder) - [`Recorder`: Recorder (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder)
- [<idp:inline class="- topic/inline " val="code" displayname="code" id="code563211231612" tempcmdid="code563211231612">JsRecorder</idp:inline>: Recorder (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/JSRecorder) - [`JsRecorder`: Recorder (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/JSRecorder)
- [<idp:inline class="- topic/inline " val="code" displayname="code" id="code7932192919168" tempcmdid="code7932192919168">eTsAudioPlayer</idp:inline>: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets) - [`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) - [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
...@@ -54,16 +54,16 @@ await cameraManager.getCameras((err, cameras) => { ...@@ -54,16 +54,16 @@ await cameraManager.getCameras((err, cameras) => {
cameraArray = cameras cameraArray = cameras
}) })
for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex) { for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex) {
console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID. console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID.
console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // Obtain the camera position. console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // Obtain the camera position.
console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type. console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type.
console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // Obtain the camera connection type. console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // Obtain the camera connection type.
} }
// Create a camera input stream. // Create a camera input stream.
let cameraInput let cameraInput
await cameraManager.createCameraInput(cameraArray[0].cameraId).then((input) => { await cameraManager.createCameraInput(cameraArray[0].cameraId).then((input) => {
console.log('Promise returned with the CameraInput instance'); console.log('Promise returned with the CameraInput instance');
cameraInput = input cameraInput = input
}) })
......
...@@ -8,13 +8,11 @@ You can use video playback APIs to convert video data into visible signals, play ...@@ -8,13 +8,11 @@ You can use video playback APIs to convert video data into visible signals, play
![en-us_image_video_state_machine](figures/en-us_image_video_state_machine.png) ![en-us_image_video_state_machine](figures/en-us_image_video_state_machine.png)
**Figure 2** Layer 0 diagram of video playback **Figure 2** Layer 0 diagram of video playback
![en-us_image_video_player](figures/en-us_image_video_player.png) ![en-us_image_video_player](figures/en-us_image_video_player.png)
Note: Video playback requires hardware capabilities such as display, audio, and codec. *Note: Video playback requires hardware capabilities such as display, audio, and codec.*
1. A third-party application obtains a surface ID from the XComponent. 1. A third-party application obtains a surface ID from the XComponent.
2. The third-party application transfers the surface ID to the VideoPlayer JS. 2. The third-party application transfers the surface ID to the VideoPlayer JS.
...@@ -43,9 +41,7 @@ The full video playback process includes creating an instance, setting the URL, ...@@ -43,9 +41,7 @@ The full video playback process includes creating an instance, setting the URL,
For details about the **url** types supported by **VideoPlayer**, see the [url attribute](../reference/apis/js-apis-media.md#videoplayer_attributes). For details about the **url** types supported by **VideoPlayer**, see the [url attribute](../reference/apis/js-apis-media.md#videoplayer_attributes).
For details about how to create an XComponent, see [XComponent](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md). For details about how to create an XComponent, see [XComponent](../reference/arkui-ts/ts-basic-components-xcomponent.md).
*Note: **setSurface** must be called after the URL is set but before **prepare** is called.
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
...@@ -120,7 +116,7 @@ export class VideoPlayerDemo { ...@@ -120,7 +116,7 @@ export class VideoPlayerDemo {
console.info('pause success'); console.info('pause success');
}, this.failureCallback).catch(this.catchCallback); }, this.failureCallback).catch(this.catchCallback);
// Use a promise to obtain the video track information. // Use a promise to obtain the video track information communication_dsoftbus.
let arrayDescription; let arrayDescription;
await videoPlayer.getTrackDescription().then((arrlist) => { await videoPlayer.getTrackDescription().then((arrlist) => {
if (typeof (arrlist) != 'undefined') { if (typeof (arrlist) != 'undefined') {
......
# Native APIs # Native APIs
- [Using Native APIs in Application Projects](napi-guidelines.md) - [Using Native APIs in Application Projects](napi-guidelines.md)
- [Drawing Development](drawing-guidelines.md)
- [Native Window Development](native-window-guidelines.md)
- [Raw File Development](rawfile-guidelines.md)
此差异已折叠。
此差异已折叠。
此差异已折叠。
...@@ -2,5 +2,8 @@ ...@@ -2,5 +2,8 @@
- [Common Event and Notification Overview](notification-brief.md) - [Common Event and Notification Overview](notification-brief.md)
- [Common Event Development](common-event.md) - [Common Event Development](common-event.md)
- [Notification Development](notification.md) - [Notification Development](notification-guidelines.md)
- Agent-Powered Scheduled Reminder
- [Agent-Powered Scheduled Reminder Overview](background-agent-scheduled-reminder-overview.md)
- [Agent-Powered Scheduled Reminder Development](background-agent-scheduled-reminder-guide.md)
- [Debugging Assistant Usage](assistant-guidelines.md) - [Debugging Assistant Usage](assistant-guidelines.md)
...@@ -2,9 +2,9 @@ ...@@ -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. 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 * Functionality
...@@ -41,7 +41,7 @@ The common event and notification module provides debugging tools to facilitate ...@@ -41,7 +41,7 @@ The common event and notification module provides debugging tools to facilitate
![cem-publish-all](figures/cem-publish-all.png) ![cem-publish-all](figures/cem-publish-all.png)
##### dump ### dump
* Functionality * Functionality
...@@ -67,7 +67,7 @@ The common event and notification module provides debugging tools to facilitate ...@@ -67,7 +67,7 @@ The common event and notification module provides debugging tools to facilitate
​ ![cem-dump-e](figures/cem-dump-e.png) ​ ![cem-dump-e](figures/cem-dump-e.png)
##### help ### help
* Functionality * Functionality
...@@ -83,9 +83,9 @@ The common event and notification module provides debugging tools to facilitate ...@@ -83,9 +83,9 @@ The common event and notification module provides debugging tools to facilitate
### anm Debugging Assistant ## anm Debugging Assistant
##### dump ### dump
* Functionality * Functionality
...@@ -119,7 +119,7 @@ The common event and notification module provides debugging tools to facilitate ...@@ -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. Set the number of the cached recent notifications to be displayed to 10.
##### help ### help
* Functionality * Functionality
......
# Agent-Powered Scheduled Reminder Overview<a name="EN-US_TOPIC_0000001139084594"></a> # Agent-Powered Scheduled Reminder Overview
Your application can 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. Your application can 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.
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册