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

Merge branch 'master' of gitee.com:openharmony/docs into 0630-b

# 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
...@@ -218,6 +218,11 @@ zh-cn/application-dev/reference/apis/js-apis-huks.md @zengyawen ...@@ -218,6 +218,11 @@ zh-cn/application-dev/reference/apis/js-apis-huks.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-system-cipher.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-system-cipher.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-data-ability.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-data-ability.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-data-ValuesBucket.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-data-dataSharePredicates.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-data-dataShare.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-distributed-data.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-distributed-data.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @ge-yafang
...@@ -309,6 +314,8 @@ zh-cn/application-dev/reference/apis/js-apis-worker.md @zengyawen ...@@ -309,6 +314,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)
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
This document provides guidance on building the Docker image for mini- and small-system devices. This document provides guidance on building the Docker image for mini- and small-system devices.
The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.huaweicloud.com/authui/login.html?service=https%3A%2F%2Fconsole.huaweicloud.com%2Fswr%2F%3Fregion%3Dcn-south-1%26cloud_route_state%3D%2Fapp%2Fwarehouse%2FwarehouseMangeDetail%2Fgoldensir%2Fopenharmony-docker%2Fopenharmony-docker%3Ftype%3DownImage&locale=en-us#/login). Using the Docker image will help simplify environment configurations needed for the building. The following table lists container-based options needed for building in the standalone Docker environment. The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.huaweicloud.com/authui/login.html?service=https%3A%2F%2Fconsole.huaweicloud.com%2Fswr%2F%3Fregion%3Dcn-south-1%26cloud_route_state%3D%2Fapp%2Fwarehouse%2FwarehouseMangeDetail%2Fgoldensir%2Fopenharmony-docker%2Fopenharmony-docker%3Ftype%3DownImage&locale=en-us#/login). Using the Docker image will help simplify environment configurations needed for the building. The following table lists container-based options needed for building in the standalone [Docker environment](https://gitee.com/openharmony/docs/blob/master/en/device-dev/get-code/gettools-acquire.md).
| Docker Image Repository | Tag | Description | | Docker Image Repository | Tag | Description |
| :----------------------------------------------------------- | :------ | :-------------------------------------------------------- | | :----------------------------------------------------------- | :------ | :-------------------------------------------------------- |
......
...@@ -21,7 +21,7 @@ OpenHarmony is designed with a layered architecture, which from bottom to top, c ...@@ -21,7 +21,7 @@ OpenHarmony is designed with a layered architecture, which from bottom to top, c
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\).
...@@ -42,42 +42,39 @@ This layer consists of system apps and third-party apps. Each OpenHarmony app is ...@@ -42,42 +42,39 @@ 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
- 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.
Intelligent Soft Bus manages apps and user data distributed across different devices. Under such management, user data is no longer bound to a single physical device, and service logic is decoupled from storage. As your apps are running across devices, their data is seamlessly transmitted from one device to another, creating a foundation for a user experience that is smooth and consistent. - Distributed Scheduler
The Distributed Scheduler is designed based on technical features such as DSoftBus, distributed data management, and distributed profile. It builds a unified distributed service management mechanism \(including service discovery, synchronization, registration, and invocation\), and supports remote startup, remote invocation, binding/unbinding, and migration of apps across devices. This way, your app can select the most suitable device to perform distributed tasks based on the capabilities, locations, running status, and resource usage of different devices, as well as user habits and intentions.
- Distributed Scheduler - Device virtualization
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.
- 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. 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.
2. **One-time development for multi-device deployment** **One-time development for multi-device deployment**
OpenHarmony provides you with the user application, ability, and UI frameworks. With these frameworks, you can develop your apps once, and then flexibly deploy them across a broad range of different devices. OpenHarmony provides you with the user application, ability, and UI frameworks. With these frameworks, you can develop your apps once, and then flexibly deploy them across a broad range of different devices.
Consistent APIs ensure the operational compatibility of apps across devices. Consistent APIs ensure the operational compatibility of apps across devices.
- Adaptation of device capabilities \(including CPU, memory, peripheral, and software resources\) can be previewed. - 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. - Resources can be scheduled based on the compatibility between user apps and the software platform.
3. **A unified OS for flexible deployment** **A unified OS for flexible deployment**
OpenHarmony enables hardware resources to be scaled with its component-based and small-scale designs. It can be deployed on demand for a diverse range of devices, including ARM, RISC-V, and x86 architectures, and providing RAM volumes ranging from hundreds of KiB to GiB. OpenHarmony enables hardware resources to be scaled with its component-based and small-scale designs. It can be deployed on demand for a diverse range of devices, including ARM, RISC-V, and x86 architectures, and providing RAM volumes ranging from hundreds of KiB to GiB.
## OS Types<a name="section145241459142416"></a> ## OS Types<a name="section145241459142416"></a>
...@@ -113,10 +110,10 @@ The following table describes the subsystems of OpenHarmony. For details about t ...@@ -113,10 +110,10 @@ The following table describes the subsystems of OpenHarmony. For details about t
| 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 |
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
## IDL Overview ## IDL Overview
To ensure successful communications between the client and server, interfaces recognized by both parties must be defined. The OpenHarmony Interface Definition Language (IDL) is a tool for defining such interfaces. OpenHarmony IDL decomposes objects to be transferred into primitives that can be understood by the operating system and encapsulates cross-boundary objects based on developers' requirements. To ensure successful communications between the client and server, interfaces recognized by both parties must be defined. The OpenHarmony Interface Definition Language (IDL) is a tool for defining such interfaces. OpenHarmony IDL decomposes objects to be transferred into primitives that can be understood by the operating system and encapsulates cross-boundary objects based on developers' requirements.
**Figure 1** IDL interface description **Figure 1** IDL interface description
![IDL-interface-description](./figures/IDL-interface-description.png) ![IDL-interface-description](./figures/IDL-interface-description.png)
...@@ -47,29 +47,34 @@ The sequenceable type is declared using the keyword **sequenceable**. This type ...@@ -47,29 +47,34 @@ The sequenceable type is declared using the keyword **sequenceable**. This type
In C++, the declaration is placed in the file header in the format of **sequenceable includedir..namespace.typename**. It can be in any of the following forms: In C++, the declaration is placed in the file header in the format of **sequenceable includedir..namespace.typename**. It can be in any of the following forms:
``` ```cpp
sequenceable includedir..namespace.typename sequenceable includedir..namespace.typename
sequenceable includedir...typename sequenceable includedir...typename
sequenceable namespace.typename sequenceable namespace.typename
``` ```
In the preceding information, **includedir** indicates the directory where the header file of the type is located, and the dot (.) is used as the separator. **namespace** indicates the namespace where the type is located, and the dot (.) is used as the separator. **typename** indicates the data type, which can contain only English characters. **includedir** and **namespace** are separated by two dots (..). If the declaration statement does not contain two dots, all characters except the last typename will be parsed as a namespace. Example: In the preceding information, **includedir** indicates the directory where the header file of the type is located, and the dot (.) is used as the separator. **namespace** indicates the namespace where the type is located, and the dot (.) is used as the separator. **typename** indicates the data type, which can contain only English characters. **includedir** and **namespace** are separated by two dots (..). If the declaration statement does not contain two dots, all characters except the last typename will be parsed as a namespace. Example:
```
```cpp
sequenceable a.b..C.D sequenceable a.b..C.D
``` ```
The preceding statement is parsed into the following code in the C++ header file: The preceding statement is parsed into the following code in the C++ header file:
```
```cpp
#include "a/b/d.h" #include "a/b/d.h"
using C::D; using C::D;
``` ```
In TS, the declaration is placed in the file header in the format of **sequenceable namespace.typename;**. It can be in the following form: In TS, the declaration is placed in the file header in the format of **sequenceable namespace.typename;**. It can be in the following form:
``` ```ts
sequenceable idl.MySequenceable sequenceable idl.MySequenceable
``` ```
In the preceding information, **namespace** indicates the namespace to which the data type belongs, **typename** indicates the data type name, and **MySequenceable** indicates that data can be passed during IPC using **Parcel** objects. The sequenceable type is not defined in the IDL file, but in the .ts file. Therefore, IDL adds the following statement to the generated .ts file based on the declaration: In the preceding information, **namespace** indicates the namespace to which the data type belongs, **typename** indicates the data type name, and **MySequenceable** indicates that data can be passed during IPC using **Parcel** objects. The sequenceable type is not defined in the IDL file, but in the .ts file. Therefore, IDL adds the following statement to the generated .ts file based on the declaration:
``` ```ts
import MySequenceable from "./my_sequenceable" import MySequenceable from "./my_sequenceable"
``` ```
...@@ -80,19 +85,19 @@ The interface type refers to interfaces defined in IDL files. The interfaces def ...@@ -80,19 +85,19 @@ The interface type refers to interfaces defined in IDL files. The interfaces def
The declaration form in C++ is similar to that of the sequenceable type. The declaration form is as follows: The declaration form in C++ is similar to that of the sequenceable type. The declaration form is as follows:
``` ```cpp
interface includedir..namespace.typename interface includedir..namespace.typename
``` ```
In TS, the declaration form is as follows: In TS, the declaration form is as follows:
``` ```ts
interface namespace.interfacename interface namespace.interfacename
``` ```
In the preceding information, **namespace** indicates the namespace to which the interface belongs, and **interfacename** indicates the name of the interface. For example, **interface OHOS.IIdlTestObserver;** declares the **IIdlTestObserver** interface defined in another IDL file. This interface can be used as the parameter type or return value type of a method in the current file. IDL adds the following statement to the generated .ts file based on the statement: In the preceding information, **namespace** indicates the namespace to which the interface belongs, and **interfacename** indicates the name of the interface. For example, **interface OHOS.IIdlTestObserver;** declares the **IIdlTestObserver** interface defined in another IDL file. This interface can be used as the parameter type or return value type of a method in the current file. IDL adds the following statement to the generated .ts file based on the statement:
``` ```ts
import IIdlTestObserver from "./i_idl_test_observer" import IIdlTestObserver from "./i_idl_test_observer"
``` ```
...@@ -101,7 +106,7 @@ The array type is represented by T[], where **T** can be the primitive, sequence ...@@ -101,7 +106,7 @@ The array type is represented by T[], where **T** can be the primitive, sequence
The table below lists the mappings between the IDL array type and TS and C++ data types. The table below lists the mappings between the IDL array type and TS and C++ data types.
|IDL Data Type | C++ Data Type | TS Data Type | |IDL Data Type | C++ Data Type | TS Data Type |
| -------- | -------- | -------- | | ------- | -------- | -------- |
|T[] | std::vector&lt;T&gt; | T[] | |T[] | std::vector&lt;T&gt; | T[] |
#### Container Type #### Container Type
...@@ -114,26 +119,32 @@ In TS, the List container type is not supported, and the Map container type is g ...@@ -114,26 +119,32 @@ In TS, the List container type is not supported, and the Map container type is g
The table below lists the mappings between the IDL container type and TS and C++ data types. The table below lists the mappings between the IDL container type and TS and C++ data types.
|IDL Data Type | C++ Data Type | TS Data Type | |IDL Data Type | C++ Data Type | TS Data Type |
| -------- | -------- | -------- | | -------- | -------- | ------- |
|List&lt;T&gt; | std::list | Not supported| |List&lt;T&gt; | std::list | Not supported |
|Map<KT,VT> | std::map | Map | |Map<KT,VT> | std::map | Map |
### Specifications for Compiling IDL Files ### Specifications for Compiling IDL Files
Only one interface type can be defined in an IDL file, and the interface name must be the same as the file name. The interface definition of the IDL file is described in Backus-Naur form (BNF). The basic definition format is as follows: Only one interface type can be defined in an IDL file, and the interface name must be the same as the file name. The interface definition of the IDL file is described in Backus-Naur form (BNF). The basic definition format is as follows:
``` ```
[<*interface_attr_declaration*>]interface<*interface_name_with_namespace*>{<*method_declaration*>} [<*interface_attr_declaration*>]interface<*interface_name_with_namespace*>{<*method_declaration*>}
``` ```
In the preceding information, <*interface_attr_declaration*> declares interface attributes. Currently, only the **oneway** attribute is supported, indicating that all methods in the interface are unidirectional. Such a method returns value without waiting for the execution to complete. This attribute is optional. If this attribute is not set, synchronous call is used. The interface name must contain the complete interface header file directory, namespace, and method declaration. Empty interfaces are not allowed. In the preceding information, <*interface_attr_declaration*> declares interface attributes. Currently, only the **oneway** attribute is supported, indicating that all methods in the interface are unidirectional. Such a method returns value without waiting for the execution to complete. This attribute is optional. If this attribute is not set, synchronous call is used. The interface name must contain the complete interface header file directory, namespace, and method declaration. Empty interfaces are not allowed.
The method declaration format in the interface is as follows: The method declaration format in the interface is as follows:
``` ```
[<*method_attr_declaration*>]<*result_type*><*method_declaration*> [<*method_attr_declaration*>]<*result_type*><*method_declaration*>
``` ```
In the preceding information, <*method_attr_declaration*> describes the interface attributes. Currently, only the **oneway** attribute is supported, indicating that the method is unidirectional. Such a method returns value without waiting for the execution to complete. This attribute is optional. If this attribute is not set, synchronous call is used. <*result_type*> indicates the type of the return value, and <*method_declaration*> indicates the method name and parameter declaration. In the preceding information, <*method_attr_declaration*> describes the interface attributes. Currently, only the **oneway** attribute is supported, indicating that the method is unidirectional. Such a method returns value without waiting for the execution to complete. This attribute is optional. If this attribute is not set, synchronous call is used. <*result_type*> indicates the type of the return value, and <*method_declaration*> indicates the method name and parameter declaration.
The parameter declaration format is as follows: The parameter declaration format is as follows:
``` ```
[<*formal_param_attr*>]<*type*><*identifier*> [<*formal_param_attr*>]<*type*><*identifier*>
``` ```
The value of <*formal_param_attr*> can be **in**, **out**, or **inout**, indicating that the parameter is an input parameter, an output parameter, or both an input and an output parameter, respectively. A **oneway** method does not allow **output** or **inout** parameters or return values. The value of <*formal_param_attr*> can be **in**, **out**, or **inout**, indicating that the parameter is an input parameter, an output parameter, or both an input and an output parameter, respectively. A **oneway** method does not allow **output** or **inout** parameters or return values.
## How to Develop ## How to Develop
...@@ -144,20 +155,20 @@ The value of <*formal_param_attr*> can be **in**, **out**, or **inout**, indicat ...@@ -144,20 +155,20 @@ The value of <*formal_param_attr*> can be **in**, **out**, or **inout**, indicat
You can use C++ to create IDL files. An example IDL file is as follows: You can use C++ to create IDL files. An example IDL file is as follows:
``` ```cpp
interface OHOS.IIdlTestService { interface OHOS.IIdlTestService {
int TestIntTransaction([in] int data); int TestIntTransaction([in] int data);
void TestStringTransaction([in] String data); void TestStringTransaction([in] String data);
} }
``` ```
You can run the **./idl -gen-cpp -d dir -c dir/iTest.idl** command (**-d** indicates the output directory) to generate the interface file, stub file, and proxy file in the **dir** directory in the execution environment. The names of the generated interface class files are the same as that of the IDL file, except that the file name extensions are **.h** and **.cpp**. For example, for **IIdlTestService.idl**, the generated files are **i_idl_test_service.h**, **idl_test_service_proxy.h**, **idl_test_service_stub.h**, **idl_test_service_proxy.cpp**, and **idl_test_service_stub.cpp**. You can run the **./idl -gen-cpp -d dir -c dir/iTest.idl** command (**-d** indicates the output directory) to generate the interface file, stub file, and proxy file in the **dir** directory in the execution environment. The names of the generated interface class files are the same as that of the IDL file, except that the file name extensions are **.h** and **.cpp**. For example, the files generated for **IIdlTestService.idl** are **i_idl_test_service.h**, **idl_test_service_proxy.h**, **idl_test_service_stub.h**, **idl_test_service_proxy.cpp**, and **idl_test_service_stub.cpp**.
#### Exposing Interfaces on the Server #### Exposing Interfaces on the Server
The stub class generated by IDL is an abstract implementation of the interface class and declares all methods in the IDL file. The stub class generated by IDL is an abstract implementation of the interface class and declares all methods in the IDL file.
``` ```cpp
#ifndef OHOS_IDLTESTSERVICESTUB_H #ifndef OHOS_IDLTESTSERVICESTUB_H
#define OHOS_IDLTESTSERVICESTUB_H #define OHOS_IDLTESTSERVICESTUB_H
#include <iremote_stub.h> #include <iremote_stub.h>
...@@ -182,7 +193,7 @@ private: ...@@ -182,7 +193,7 @@ private:
You need to inherit the interface class defined in the IDL file and implement the methods in the class. In addition, you need to register the defined services with SAMGR during service initialization. In the following code snippet, **TestService** inherits the **IdlTestServiceStub** interface class and implements the **TestIntTransaction** and **TestStringTransaction** methods. You need to inherit the interface class defined in the IDL file and implement the methods in the class. In addition, you need to register the defined services with SAMGR during service initialization. In the following code snippet, **TestService** inherits the **IdlTestServiceStub** interface class and implements the **TestIntTransaction** and **TestStringTransaction** methods.
``` ```cpp
#ifndef OHOS_IPC_TEST_SERVICE_H #ifndef OHOS_IPC_TEST_SERVICE_H
#define OHOS_IPC_TEST_SERVICE_H #define OHOS_IPC_TEST_SERVICE_H
...@@ -207,7 +218,7 @@ private: ...@@ -207,7 +218,7 @@ private:
The sample code for registering a service is as follows: The sample code for registering a service is as follows:
``` ```cpp
#include "test_service.h" #include "test_service.h"
#include <string_ex.h> #include <string_ex.h>
...@@ -259,12 +270,11 @@ ErrCode TestService::TestStringTransaction(const std::string &data) ...@@ -259,12 +270,11 @@ ErrCode TestService::TestStringTransaction(const std::string &data)
} // namespace OHOS } // namespace OHOS
``` ```
#### Calling Methods from the Client for IPC #### Calling Methods from the Client for IPC
The C++ client obtains the service proxy defined in the system through SAMGR and then invokes the interface provided by the proxy. The sample code is as follows: The C++ client obtains the service proxy defined in the system through SAMGR and then invokes the interface provided by the proxy. The sample code is as follows:
``` ```cpp
#include "test_client.h" #include "test_client.h"
#include "if_system_ability_manager.h" #include "if_system_ability_manager.h"
...@@ -316,16 +326,13 @@ void TestClient::StartStringTransaction() ...@@ -316,16 +326,13 @@ void TestClient::StartStringTransaction()
} // namespace OHOS } // namespace OHOS
``` ```
### Development Using TS ### Development Using TS
#### Creating an IDL File #### Creating an IDL File
You can use TS to create IDL files. An example IDL file is as follows: You can use TS to create IDL files. An example IDL file is as follows:
``` ```ts
interface OHOS.IIdlTestService { interface OHOS.IIdlTestService {
int TestIntTransaction([in] int data); int TestIntTransaction([in] int data);
void TestStringTransaction([in] String data); void TestStringTransaction([in] String data);
...@@ -338,7 +345,7 @@ Run the **./idl -c IIdlTestService.idl -gen-ts -d /data/ts/** command (**-d** in ...@@ -338,7 +345,7 @@ Run the **./idl -c IIdlTestService.idl -gen-ts -d /data/ts/** command (**-d** in
The stub class generated by IDL is an abstract implementation of the interface class and declares all methods in the IDL file. The stub class generated by IDL is an abstract implementation of the interface class and declares all methods in the IDL file.
``` ```ts
import {testIntTransactionCallback} from "./i_idl_test_service"; import {testIntTransactionCallback} from "./i_idl_test_service";
import {testStringTransactionCallback} from "./i_idl_test_service"; import {testStringTransactionCallback} from "./i_idl_test_service";
import IIdlTestService from "./i_idl_test_service"; import IIdlTestService from "./i_idl_test_service";
...@@ -387,7 +394,7 @@ export default class IdlTestServiceStub extends rpc.RemoteObject implements IIdl ...@@ -387,7 +394,7 @@ export default class IdlTestServiceStub extends rpc.RemoteObject implements IIdl
You need to inherit the interface class defined in the IDL file and implement the methods in the class. The following code snippet shows how to inherit the **IdlTestServiceStub** interface class and implement the **testIntTransaction** and **testStringTransaction** methods. You need to inherit the interface class defined in the IDL file and implement the methods in the class. The following code snippet shows how to inherit the **IdlTestServiceStub** interface class and implement the **testIntTransaction** and **testStringTransaction** methods.
``` ```ts
import {testIntTransactionCallback} from "./i_idl_test_service" import {testIntTransactionCallback} from "./i_idl_test_service"
import {testStringTransactionCallback} from "./i_idl_test_service" import {testStringTransactionCallback} from "./i_idl_test_service"
import IdlTestServiceStub from "./idl_test_service_stub" import IdlTestServiceStub from "./idl_test_service_stub"
...@@ -408,7 +415,7 @@ class IdlTestImp extends IdlTestServiceStub { ...@@ -408,7 +415,7 @@ class IdlTestImp extends IdlTestServiceStub {
After the service implements the interface, the interface needs to be exposed to the client for connection. If your service needs to expose this interface, extend **Ability** and implement **onConnect()** to return **IRemoteObject** so that the client can interact with the service process. The following code snippet shows how to expose the **IRemoteAbility** interface to the client: After the service implements the interface, the interface needs to be exposed to the client for connection. If your service needs to expose this interface, extend **Ability** and implement **onConnect()** to return **IRemoteObject** so that the client can interact with the service process. The following code snippet shows how to expose the **IRemoteAbility** interface to the client:
``` ```ts
export default { export default {
onStart() { onStart() {
console.info('ServiceAbility onStart'); console.info('ServiceAbility onStart');
...@@ -442,7 +449,7 @@ export default { ...@@ -442,7 +449,7 @@ export default {
When the client calls **connectAbility()** to connect to a Service ability, the **onConnect** callback in **onAbilityConnectDone** of the client receives the **IRemoteObject** instance returned by the **onConnect()** method of the Service ability. The client and Service ability are in different applications. Therefore, the directory of the client application must contain a copy of the .idl file (the SDK automatically generates the proxy class). The **onConnect** callback then uses the **IRemoteObject** instance to create the **testProxy** instance of the **IdlTestServiceProxy** class and calls the related IPC method. The sample code is as follows: When the client calls **connectAbility()** to connect to a Service ability, the **onConnect** callback in **onAbilityConnectDone** of the client receives the **IRemoteObject** instance returned by the **onConnect()** method of the Service ability. The client and Service ability are in different applications. Therefore, the directory of the client application must contain a copy of the .idl file (the SDK automatically generates the proxy class). The **onConnect** callback then uses the **IRemoteObject** instance to create the **testProxy** instance of the **IdlTestServiceProxy** class and calls the related IPC method. The sample code is as follows:
``` ```ts
import IdlTestServiceProxy from './idl_test_service_proxy' import IdlTestServiceProxy from './idl_test_service_proxy'
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
...@@ -495,7 +502,7 @@ To create a class that supports the sequenceable type, perform the following ope ...@@ -495,7 +502,7 @@ To create a class that supports the sequenceable type, perform the following ope
The following is an example of the **MySequenceable** class code: The following is an example of the **MySequenceable** class code:
``` ```ts
import rpc from '@ohos.rpc'; import rpc from '@ohos.rpc';
export default class MySequenceable { export default class MySequenceable {
constructor(num: number, str: string) { constructor(num: number, str: string) {
...@@ -523,8 +530,6 @@ export default class MySequenceable { ...@@ -523,8 +530,6 @@ export default class MySequenceable {
} }
``` ```
## How to Develop for Interworking Between C++ and TS ## How to Develop for Interworking Between C++ and TS
### TS Proxy and C++ Stub Development ### TS Proxy and C++ Stub Development
...@@ -535,7 +540,7 @@ export default class MySequenceable { ...@@ -535,7 +540,7 @@ export default class MySequenceable {
2. Create a service object, inherit the interface class defined in the C++ stub file, and implement the methods in the class. An example is as follows: 2. Create a service object, inherit the interface class defined in the C++ stub file, and implement the methods in the class. An example is as follows:
``` ```cpp
class IdlTestServiceImpl : public IdlTestServiceStub { class IdlTestServiceImpl : public IdlTestServiceStub {
public: public:
IdlTestServiceImpl() = default; IdlTestServiceImpl() = default;
...@@ -558,7 +563,7 @@ export default class MySequenceable { ...@@ -558,7 +563,7 @@ export default class MySequenceable {
C++ provides C++ service objects to TS in the format of native APIs. For example, C++ provides a **GetNativeObject** method, which is used to create an **IdlTestServiceImpl** instance. Using the **NAPI_ohos_rpc_CreateJsRemoteObject** method, you can create a JS remote object for the TS application. C++ provides C++ service objects to TS in the format of native APIs. For example, C++ provides a **GetNativeObject** method, which is used to create an **IdlTestServiceImpl** instance. Using the **NAPI_ohos_rpc_CreateJsRemoteObject** method, you can create a JS remote object for the TS application.
``` ```cpp
NativeValue* GetNativeObject(NativeEngine& engine, NativeCallbackInfo& info) NativeValue* GetNativeObject(NativeEngine& engine, NativeCallbackInfo& info)
{ {
sptr<IdlTestServiceImpl> impl = new IdlTestServiceImpl(); sptr<IdlTestServiceImpl> impl = new IdlTestServiceImpl();
...@@ -572,8 +577,7 @@ NativeValue* GetNativeObject(NativeEngine& engine, NativeCallbackInfo& info) ...@@ -572,8 +577,7 @@ NativeValue* GetNativeObject(NativeEngine& engine, NativeCallbackInfo& info)
Use TS to construct an IDL file and run commands to generate interfaces, stub files, and proxy files. An example proxy file is as follows: Use TS to construct an IDL file and run commands to generate interfaces, stub files, and proxy files. An example proxy file is as follows:
``` ```ts
import {testIntTransactionCallback} from "./i_idl_test_service"; import {testIntTransactionCallback} from "./i_idl_test_service";
import {testStringTransactionCallback} from "./i_idl_test_service"; import {testStringTransactionCallback} from "./i_idl_test_service";
import IIdlTestService from "./i_idl_test_service"; import IIdlTestService from "./i_idl_test_service";
...@@ -634,7 +638,7 @@ export default class IdlTestServiceProxy implements IIdlTestService { ...@@ -634,7 +638,7 @@ export default class IdlTestServiceProxy implements IIdlTestService {
2. Construct a TS proxy and transfers the remote C++ service object to it. 2. Construct a TS proxy and transfers the remote C++ service object to it.
3. Use the TS proxy to call the method declared in the IDL file to implement the interworking between the TS proxy and C++ stub. The following is an example: 3. Use the TS proxy to call the method declared in the IDL file to implement the interworking between the TS proxy and C++ stub. The following is an example:
``` ```ts
import IdlTestServiceProxy from './idl_test_service_proxy' import IdlTestServiceProxy from './idl_test_service_proxy'
import nativeMgr from 'nativeManager'; import nativeMgr from 'nativeManager';
......
...@@ -20,7 +20,6 @@ ...@@ -20,7 +20,6 @@
- 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)
...@@ -29,9 +28,7 @@ ...@@ -29,9 +28,7 @@
- [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)
- [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)
- [Work Scheduler](work-scheduler/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)
...@@ -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.
...@@ -13,8 +13,8 @@ The stage model is designed to make it easier to develop complex applications in ...@@ -13,8 +13,8 @@ The stage model is designed to make it easier to develop complex applications in
| -------------- | ------------------------------------------------------------ | -------------------------------------------------------- | | -------------- | ------------------------------------------------------------ | -------------------------------------------------------- |
| 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:
...@@ -29,3 +29,6 @@ In addition, the following differences exist in the development process: ...@@ -29,3 +29,6 @@ In addition, the following differences exist in the development process:
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).
## 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
......
...@@ -6,11 +6,12 @@ ...@@ -6,11 +6,12 @@
The OpenHarmony application framework has two models: Feature Ability (FA) model and stage model. Correspondingly, there are two sets of context mechanisms. **application/BaseContext** is a common context base class. It uses the **stageMode** attribute to specify whether the context is used for the stage model. The OpenHarmony application framework has two models: Feature Ability (FA) model and stage model. Correspondingly, there are two sets of context mechanisms. **application/BaseContext** is a common context base class. It uses the **stageMode** attribute to specify whether the context is used for the stage model.
- FA Model - FA model
Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance. Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance.
- Stage Model - Stage model
The stage model has the following types of contexts: **application/Context**, **application/ApplicationContext**, **application/AbilityStageContext**, **application/ExtensionContext**, **application/AbilityContext**, and **application/FormExtensionContext**. For details about these contexts and how to use them, see [Context in the Stage Model](#context-in-the-stage-model). The stage model has the following types of contexts: **application/Context**, **application/ApplicationContext**, **application/AbilityStageContext**, **application/ExtensionContext**, **application/AbilityContext**, and **application/FormExtensionContext**. For details about these contexts and how to use them, see [Context in the Stage Model](#context-in-the-stage-model).
...@@ -45,6 +46,34 @@ export default { ...@@ -45,6 +46,34 @@ export default {
} }
``` ```
### Common Context-related Methods in the FA Model
The following context-related methods are available in the FA model:
```javascript
setDisplayOrientation(orientation: bundle.DisplayOrientation, callback: AsyncCallback<void>): void
setDisplayOrientation(orientation: bundle.DisplayOrientation): Promise<void>;
```
The methods are used to set the display orientation of the current ability.
**Example**
```javascript
import featureAbility from '@ohos.ability.featureAbility'
import bundle from '../@ohos.bundle';
export default {
onCreate() {
// Obtain the context and call related APIs.
let context = featureAbility.getContext();
context.setDisplayOrientation(bundle.DisplayOrientation.LANDSCAPE).then(() => {
console.log("Set display orientation.")
})
console.info('Application onCreate')
},
onDestroy() {
console.info('Application onDestroy')
},
}
```
## Context in the Stage Model ## Context in the Stage Model
The following describes the contexts provided by the stage model in detail. The following describes the contexts provided by the stage model in detail.
...@@ -195,7 +224,7 @@ export default class MainAbility extends Ability { ...@@ -195,7 +224,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 |
| ------------ | ------------------------------------------------------------ | | ------------ | ------------------------------------------------------------ |
...@@ -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 Storing Widget Data
Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget. Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting 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,9 +223,11 @@ You should override **onDestroy** to delete widget data. ...@@ -230,9 +223,11 @@ 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);
} }
``` ```
...@@ -240,16 +235,16 @@ For details about the persistence method, see [Lightweight Data Store Developmen ...@@ -240,16 +235,16 @@ For details about the persistence method, see [Lightweight Data Store Developmen
Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one. 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)
...@@ -86,8 +86,10 @@ By default, **singleton** is used. ...@@ -86,8 +86,10 @@ By default, **singleton** is used.
); );
``` ```
### Starting a Remote Page Ability (Applying only to System Applications) ### Starting a Remote Page Ability
>Note: The **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. Therefore, remote Page ability startup applies only to system applications. >Note
>
>This feature applies only to system applications, since the **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications.
**Modules to Import** **Modules to Import**
...@@ -155,8 +157,7 @@ In the cross-device scenario, the application must also apply for the data synch ...@@ -155,8 +157,7 @@ In the cross-device scenario, the application must also apply for the data synch
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]);
} }
} }
......
...@@ -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');
...@@ -44,7 +43,7 @@ A Service ability is used to run tasks in the background, such as playing music ...@@ -44,7 +43,7 @@ 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,13 +119,24 @@ After the preceding code is executed, the **startAbility()** API is called to st ...@@ -105,13 +119,24 @@ 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).
2. Writing code in the corresponding file
When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails.
The following code snippet shows how to implement the callbacks:
```javascript
import prompt from '@system.prompt'
let mRemote;
function onConnectCallback(element, remote){
console.log('onConnectLocalService onConnectDone element: ' + element); console.log('onConnectLocalService onConnectDone element: ' + element);
console.log('onConnectLocalService onConnectDone remote: ' + remote); console.log('onConnectLocalService onConnectDone remote: ' + remote);
mRemote = remote; mRemote = remote;
...@@ -137,43 +162,43 @@ function onConnectCallback(element, remote){ ...@@ -137,43 +162,43 @@ function onConnectCallback(element, remote){
console.log('sendRequest error:' + 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) {
...@@ -210,19 +235,24 @@ export default { ...@@ -210,19 +235,24 @@ export default {
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
...@@ -38,9 +39,10 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -38,9 +39,10 @@ The following table lists the APIs used for ability continuation. For details ab
* Configure the application startup type.
Set **launchType** in the **module.json5** to **standard**. Currently, only multi-instance applications can be continued on another device. - Configure the application startup type.
Set **launchType** in the **module.json5** file to **standard** to add multi-instance support to the application.
```javascript ```javascript
"launchType": "standard" "launchType": "standard"
...@@ -48,7 +50,8 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -48,7 +50,8 @@ The following table lists the APIs used for ability continuation. For details ab
* 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.
...@@ -59,6 +62,8 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -59,6 +62,8 @@ The following table lists the APIs used for ability continuation. For details ab
}, },
``` ```
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: 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 ```javascript
...@@ -100,9 +105,11 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -100,9 +105,11 @@ The following table lists the APIs used for ability continuation. For details ab
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,15 +118,14 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -111,15 +118,14 @@ 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
...@@ -128,24 +134,22 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -128,24 +134,22 @@ The following table lists the APIs used for ability continuation. For details ab
3. Implement the continuation logic in the **onCreate** API. 3. Implement the continuation logic in the **onCreate()** API.
The **onCreate** API is called by the **target**. When the ability is started on the target device, this API is called to instruct the application to synchronize the memory data and UI component status, and triggers page restoration after the synchronization is complete. If the continuation logic is not implemented, the ability will be started in common startup mode and the page cannot be restored. The **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.
- The target device determines whether the startup is **LaunchReason.CONTINUATION** based on **launchReason** in **onCreate**. The target device determines whether the startup is **LaunchReason.CONTINUATION** based on **launchReason** in **onCreate()**.
After data restore is complete, call **restoreWindowStage** to trigger page restoration.
- After data restore is complete, call **restoreWindowStage** to trigger page restoration. Example
* 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,13 +163,13 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -159,13 +163,13 @@ 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';
...@@ -187,10 +191,11 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -187,10 +191,11 @@ The following table lists the APIs used for ability continuation. For details ab
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.
- 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 ```javascript
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
...@@ -223,7 +228,3 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -223,7 +228,3 @@ The following table lists the APIs used for ability continuation. For details ab
} }
} }
``` ```
For details about the complete example, see the sample.
# 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. For details about the data types and parameters of **WantAgentInfo**, see [WantAgent Module](../reference/apis/js-apis-wantAgent.md#wantagentinfo). 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).
```javascript ```
private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations. private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations.
//wantAgentInfo //wantAgentInfo
var wantAgentInfo = { var wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: "", deviceId: "",
...@@ -40,34 +34,53 @@ var wantAgentInfo = { ...@@ -40,34 +34,53 @@ var wantAgentInfo = {
parameters: {} parameters: {}
} }
], ],
operationType: OperationType.START_ABILITY, operationType: wantAgent.OperationType.START_ABILITY,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgentFlags.CONSTANT_FLAG] wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
} }
``` ```
3. Create a **WantAgent** object and save the returned **wantAgentObj** for subsequent trigger operations. 3. Create a **WantAgentInfo** object for publishing a common event.
```javascript ```
// Create a WantAgent object. private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations.
wantAgent.getWantAgent(wantAgentInfo, (err, wantAgentObj) => {
//wantAgentInfo
var wantAgentInfo = {
wants: [
{
action: "event_name", // Set the action name.
parameters: {}
}
],
operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
requestCode: 0,
wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
}
```
4. Create a **WantAgent** object and save the returned **wantAgentObj** for subsequent trigger operations.
```
// Create a WantAgent object.
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,7 +138,9 @@ The following example shows how to implement a distributed data object synchroni ...@@ -91,7 +138,9 @@ 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) {
...@@ -108,8 +157,9 @@ The following example shows how to implement a distributed data object synchroni ...@@ -108,8 +157,9 @@ The following example shows how to implement a distributed data object synchroni
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.
- Callback
```js ```js
// Unsubscribe from the specified status change callback. // Save a distributed data object.
local_object.off("status", statusCallback); local_object.save("local", (result, data)=>{
// Unsubscribe from all status change callbacks. console.log("save callback");
local_object.off("status"); 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
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
// 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 ```js
local_object.setSessionId(""); // 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.
## Samples 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)
...@@ -13,21 +13,28 @@ Currently you can have access to statistics on the application usage, and notifi ...@@ -13,21 +13,28 @@ Currently you can have access to statistics on the application usage, and notifi
- **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 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 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) 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 5. Priority group of the current invoker application
6. Whether a specific application is in the idle state 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
- **The setters can be used to:**
Set the group for the application specified by **bundleName**.
- **The registration APIs can be used to:**
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.
7. The number of FA usage records specified by **maxNum**, sorted by time (most recent first) - **The deregistration APIs can be used to:**
If **maxNum** is not specified, the default value **1000** will be used. Deregister the callback for application group changes.
### 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> | 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:
...@@ -212,5 +153,3 @@ You can set a USB device as a host to connect to a device for data transfer. The ...@@ -212,5 +153,3 @@ You can set a USB device as a host to connect to a device for data transfer. The
usb.releaseInterface(pipe, interface); usb.releaseInterface(pipe, interface);
usb.closePipe(pipe); usb.closePipe(pipe);
``` ```
\ No newline at end of file
...@@ -8,14 +8,14 @@ You can set different vibration effects as needed, for example, customizing the ...@@ -8,14 +8,14 @@ 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
......
...@@ -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.
```
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.
```js
var audioStreamInfo = { var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1, channels: audio.AudioChannel.CHANNEL_1,
...@@ -39,10 +42,10 @@ Here's an example of how to use AudioCapturer to capture a raw audio file. ...@@ -39,10 +42,10 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
var state = audioRenderer.state; var state = audioRenderer.state;
``` ```
2. (Optional) Subscribe to audio capturer state change events using the **on('stateChange')** API. 2. (Optional) Use **on('stateChange')** to subscribe to audio renderer state changes.
If an application wants to take some action based on the state updates in capturer, the application can subscribe to the state change event. 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).
There are more events that applications can subscribe to, such as 'markReach' and 'periodReach'. Refer to [Audio](../reference/apis/js-apis-audio.md) for more details.
``` ```js
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) {
...@@ -68,31 +71,33 @@ Here's an example of how to use AudioCapturer to capture a raw audio file. ...@@ -68,31 +71,33 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
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.
``` The capturer state will be **STATE_RUNNING** once the audio capturer is started. The application can then begin reading buffers.
```js
await audioCapturer.start(); await audioCapturer.start();
if (audioCapturer.state == audio.AudioState.STATE_RUNNING) { if (audioCapturer.state == audio.AudioState.STATE_RUNNING) {
console.info('AudioRecLog: Capturer started'); console.info('AudioRecLog: Capturer started');
} else { } else {
console.info('AudioRecLog: Capturer start failed'); console.info('AudioRecLog: Capturer start failed');
} }
``` ```
4. Obtain the minimum buffer size to read using the **getBufferSize()** API. 4. Use **getBufferSize()** to obtain the minimum buffer size to read.
```
```js
var bufferSize = await audioCapturer.getBufferSize(); var bufferSize = await audioCapturer.getBufferSize();
console.info('AudioRecLog: buffer size: ' + bufferSize); console.info('AudioRecLog: buffer size: ' + bufferSize);
``` ```
5. Read the captured audio data and convert it to a byte stream. Call the **read()** API repeatedly to read the data 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.
until the application wants to stop the recording. The following example shows how to write recorded data into a file.
``` The following example shows how to write recorded data into a file.
```js
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
const path = '/data/data/.pulse_dir/capture_js.wav'; const path = '/data/data/.pulse_dir/capture_js.wav';
...@@ -123,7 +128,9 @@ Here's an example of how to use AudioCapturer to capture a raw audio file. ...@@ -123,7 +128,9 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
numBuffersToCapture--; numBuffersToCapture--;
} }
``` ```
6. Once the recording is complete, call the **stop()** API on the AudioCapturer instance to stop the recording.
6. Once the recording is complete, call **stop()** to stop the recording.
``` ```
await audioCapturer.stop(); await audioCapturer.stop();
if (audioCapturer.state == audio.AudioState.STATE_STOPPED) { if (audioCapturer.state == audio.AudioState.STATE_STOPPED) {
...@@ -133,8 +140,9 @@ Here's an example of how to use AudioCapturer to capture a raw audio file. ...@@ -133,8 +140,9 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
} }
``` ```
7. After the recording task is complete, call the **release()** API on the AudioCapturer instance to release the stream resources. 7. After the task is complete, call **release()** to release related resources.
```
```js
await audioCapturer.release(); await audioCapturer.release();
if (audioCapturer.state == audio.AudioState.STATE_RELEASED) { if (audioCapturer.state == audio.AudioState.STATE_RELEASED) {
console.info('AudioRecLog: Capturer released'); console.info('AudioRecLog: Capturer released');
...@@ -142,11 +150,3 @@ Here's an example of how to use AudioCapturer to capture a raw audio file. ...@@ -142,11 +150,3 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
console.info('AudioRecLog: Capturer release failed'); console.info('AudioRecLog: Capturer release failed');
} }
``` ```
## **Importance of State Check**
Application developers should keep in mind that an AudioCapturer is state-based.
That is, the AudioCapturer has an internal state that the application must always check when calling recorder control APIs, because some operations are only acceptable while the capturer is in a given state.\
The system may throw an error/exception or generate other undefined behaviour if the application performs an operation while capturer is in an improper state.
## **Other APIs**
See [AudioCapturer in the Audio API](../reference/apis/js-apis-audio.md) for more useful APIs like **getAudioTime**, **getCapturerInfo** and **getStreamInfo**.
# 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**
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 is a process to obtain discrete-time signals by extracting samples from analog signals in a continuous time domain at a specific interval.
- **Sampling rate** - **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 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** - **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. 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 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. 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** - **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.
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)
# Audio Rendering Development # Audio Rendering Development
--- ## When to Use
## ***Note***:
1. This document applies to JavaScript. **AudioRenderer** provides APIs for rendering audio files and controlling playback. It also supports audio interruption. You can use the APIs provided by **AudioRenderer** to play audio files in output devices and manage playback tasks.
---
## **Summary** ### Audio Interruption
This guide will show you how to use AudioRenderer to create an audio player app.
You can use the APIs provided in this document to play audio files in output devices and manage playback tasks. When an audio stream with a higher priority needs to be played, the audio renderer interrupts the stream with a lower priority. For example, if a call comes in when the user is listening to music, the music playback, which is the lower priority stream, is paused. For details, see [How to Develop](#how-to-develop).
## **AudioRenderer Framework** ### State Check
The AudioRenderer interface is one of the most important components of the audio framework.
### **Audio Rendering:** During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioRenderer** instance. This is because some operations can be performed only when the audio renderer is in a given state. If the application performs an operation when the audio renderer is not in the given state, the system may throw an exception or generate other undefined behavior.
The AudioRenderer framework provides APIs for playing audio files and controlling the playback.
### **Audio Interruption:** **Figure 1** Audio renderer state
When a higher priority stream wants to play, the AudioRenderer framework interrupts the lower priority stream.\
For example, if a call is arrived when you listen to music, the music playback, which is the lower priority stream, is paused.\ ![](figures/audio-renderer-state.png)
With the sample code below, we'll look at how AudioInterrupt works in detail.\
<br/> ### Asynchronous Operations
Please see [AudioRenderer in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8) for a list of supported audio stream types and formats, such as AudioSampleFormat, AudioChannel, AudioSampleFormat, and AudioEncodingType.
To ensure that the UI thread is not blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8).
## **Usage** ## How to Develop
Here's an example of how to use AudioRenderer to play a raw audio file.
1. Use **createAudioRenderer** to create an AudioRenderer instance. Renderer parameters can be set in **audioRendererOptions**.\ 1. Use **createAudioRenderer()** to create an **AudioRenderer** instance.
This object can be used to play, control, and obtain the status of the playback, as well as receive callback notifications. Set parameters of the audio renderer in **audioCapturerOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification.
```
```js
var audioStreamInfo = { var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1, channels: audio.AudioChannel.CHANNEL_1,
...@@ -46,48 +47,15 @@ Here's an example of how to use AudioRenderer to play a raw audio file. ...@@ -46,48 +47,15 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); let audioRenderer = await audio.createAudioRenderer(audioRendererOptions);
``` ```
2. Subscribe to audio interruption events using the **on** API.\ 2. Use **on('interrupt')** to subscribe to audio interruption events.
Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device.\
In some cases, the framework takes forced actions like pausing and ducking, and notifies the app using **InterruptEvent**. In other cases, the app can take action. In this situation, the app can choose to act on the **InterruptEvent** or ignore it. When the app is interrupted by forced action, it should handle the state, update the user interface, and so on.
In case of audio interrupts, the app may encounter write failures. Interrupt unaware apps can check the renderer state using the **audioRenderer.state** API before writing audio data, whereas interrupt aware apps will have more details accessible via this listener.\
<br/>
The following information will be provided by the Interrupt Event Notification:
1) **eventType:** Whether the interruption has begun or ended.
| Value | Description |
| :------------------- | :-------------------------------------------- |
| INTERRUPT_TYPE_BEGIN | Indicates that the interruption has started. |
| INTERRUPT_TYPE_END | Indicates that the interruption has finished. |
2) **forceType:** Whether the framework has already taken action or if the app is being suggested to take action.
| Value | Description |
| :-------------- | :------------------------------------------------------------------ |
| INTERRUPT_FORCE | The audio state has been changed by the framework. |
| INTERRUPT_SHARE | The app can decide whether or not to respond to the InterruptEvent. |
3) **hintType:** The kind of action taken or to be taken.
| Value | Description | Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device.
| :-------------------- | :--------------------------- |
| INTERRUPT_HINT_PAUSE | Pausing the playback. |
| INTERRUPT_HINT_RESUME | Resuming the playback. |
| INTERRUPT_HINT_STOP | Stopping the playback. |
| INTERRUPT_HINT_DUCK | Ducking the stream volume. |
| INTERRUPT_HINT_UNDUCK | Unducking the stream volume. |
4) **Some actions are exclusively forced or shared**, which means that they are performed by either the framework or the app.\ In some cases, the audio renderer performs forcible operations such as pausing and ducking, and notifies the application through **InterruptEvent**. In other cases, the application can choose to act on the **InterruptEvent** or ignore it.
For instance, when a call is received while a music stream is ongoing, the framework forces the music stream to pause. When the call is finished, the framework will not forcibly resume the music stream. Instead, it will alert the app to resume the playback.
| Action | Description | In the case of audio interruption, the application may encounter write failures. To avoid such failures, interruption unaware applications can use **audioRenderer.state** to check the renderer state before writing audio data. The applications can obtain more details by subscribing to the audio interruption events. For details, see [InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9).
| :-------------------- | :-------------------------------------------------------------------------------- |
| INTERRUPT_HINT_RESUME | INTERRUPT_SHARE is always the forceType. It can only be done by the app. |
| INTERRUPT_HINT_DUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. |
| INTERRUPT_HINT_UNDUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. |
``` ```js
audioRenderer.on('interrupt', (interruptEvent) => { audioRenderer.on('interrupt', (interruptEvent) => {
console.info('InterruptEvent Received'); console.info('InterruptEvent Received');
console.info('InterruptType: ' + interruptEvent.eventType); console.info('InterruptType: ' + interruptEvent.eventType);
...@@ -133,12 +101,14 @@ Here's an example of how to use AudioRenderer to play a raw audio file. ...@@ -133,12 +101,14 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
}); });
``` ```
4. Call the **start()** function on the AudioRenderer instance to start/resume the playback task.\ 3. Use **start()** to start audio rendering.
The renderer state will be STATE_RUNNING once the start is complete. You can then begin writing buffers.
``` The renderer state will be **STATE_RUNNING** once the audio renderer is started. The application can then begin reading buffers.
```js
async function startRenderer() { async function startRenderer() {
var state = audioRenderer.state; var state = audioRenderer.state;
// state should be prepared, paused or stopped. // The state should be prepared, paused, or stopped.
if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED ||
state != audio.AudioState.STATE_STOPPED) { state != audio.AudioState.STATE_STOPPED) {
console.info('Renderer is not in a correct state to start'); console.info('Renderer is not in a correct state to start');
...@@ -154,11 +124,13 @@ Here's an example of how to use AudioRenderer to play a raw audio file. ...@@ -154,11 +124,13 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
console.error('Renderer start failed'); console.error('Renderer start failed');
} }
} }
```
5. Make **write** calls to start rendering the buffers.
Read the audio data to be played into a buffer. Call the write function repeatedly to write data.
``` ```
4. Call **write()** to write data to the buffer.
Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer.
```js
async function writeBuffer(buf) { async function writeBuffer(buf) {
var state = audioRenderer.state; var state = audioRenderer.state;
if (state != audio.AudioState.STATE_RUNNING) { if (state != audio.AudioState.STATE_RUNNING) {
...@@ -201,8 +173,9 @@ Here's an example of how to use AudioRenderer to play a raw audio file. ...@@ -201,8 +173,9 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
} , 30); // interval to be set based on audio file format } , 30); // interval to be set based on audio file format
``` ```
6. (Optional) Call the **pause()** or **stop()** function on the AudioRenderer instance. 5. (Optional) Call **pause()** or **stop()** to pause or stop rendering.
```
```js
async function pauseRenderer() { async function pauseRenderer() {
var state = audioRenderer.state; var state = audioRenderer.state;
if (state != audio.AudioState.STATE_RUNNING) { if (state != audio.AudioState.STATE_RUNNING) {
...@@ -235,12 +208,14 @@ Here's an example of how to use AudioRenderer to play a raw audio file. ...@@ -235,12 +208,14 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
} else { } else {
console.error('Renderer stop failed'); console.error('Renderer stop failed');
} }
} }
``` ```
6. After the task is complete, call **release()** to release related resources.
**AudioRenderer** uses a large number of system resources. Therefore, ensure that the resources are released after the task is complete.
7. After the playback task is complete, call the **release()** function on the AudioRenderer instance to release resources.\ ```js
AudioRenderer can use a lot of system resources. As a result, whenever the resources are no longer required, they must be released. To ensure that any system resources allocated to it are appropriately released, you should always call **release()**.
```
async function releaseRenderer() { async function releaseRenderer() {
if (state_ == RELEASED || state_ == NEW) { if (state_ == RELEASED || state_ == NEW) {
console.info('Resourced already released'); console.info('Resourced already released');
...@@ -257,18 +232,4 @@ Here's an example of how to use AudioRenderer to play a raw audio file. ...@@ -257,18 +232,4 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
} }
} }
``` ```
## **Importance of State Check:**
You should also keep in mind that an AudioRenderer is state-based.
That is, the AudioRenderer has an internal state that you must always check when calling playback control APIs, because some operations are only acceptable while the renderer is in a given state.\
The system may throw an error/exception or generate other undefined behaviour if you perform an operation while in the improper state.\
## **Asynchronous Operations:**
Most of the AudioRenderer calls are asynchronous. As a result, the UI thread will not be blocked.\
For each API, the framework provides both callback and promises functions.\
In the example, promise functions are used for simplicity. [AudioRender in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8)
provides reference for both callback and promise.
## **Other APIs:**
See [Audio](../reference/apis/js-apis-audio.md) for more useful APIs like getAudioTime, drain, and getBufferSize.
...@@ -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)
# Drawing Development
## When to Use
The Native Drawing module provides APIs for drawing 2D graphics and text. The following scenarios are common for drawing development:
* Drawing 2D graphics
* Drawing and painting text
## Available APIs
| API| Description|
| -------- | -------- |
| OH_Drawing_BitmapCreate (void) | Creates a bitmap object.|
| OH_Drawing_BitmapBuild (OH_Drawing_Bitmap *, const uint32_t width, const uint32_t height, const OH_Drawing_BitmapFormat *) | Initializes the width and height of a bitmap object and sets the pixel format for the bitmap.|
| OH_Drawing_CanvasCreate (void) | Creates a canvas object.|
| OH_Drawing_CanvasBind (OH_Drawing_Canvas *, OH_Drawing_Bitmap *) | Binds a bitmap to a canvas so that the content drawn on the canvas is output to the bitmap (this process is called CPU rendering).|
| OH_Drawing_CanvasAttachBrush (OH_Drawing_Canvas *, const OH_Drawing_Brush *) | Attaches a brush to a canvas so that the canvas will use the style and color of the brush to fill in a shape.|
| OH_Drawing_CanvasAttachPen (OH_Drawing_Canvas *, const OH_Drawing_Pen *) | Attaches a pen to a canvas so that the canvas will use the style and color of the pen to outline a shape.|
| OH_Drawing_CanvasDrawPath (OH_Drawing_Canvas *, const OH_Drawing_Path *) | Draws a path.|
| OH_Drawing_PathCreate (void) | Creates a path object.|
| OH_Drawing_PathMoveTo (OH_Drawing_Path *, float x, float y) | Sets the start point of a path.|
| OH_Drawing_PathLineTo (OH_Drawing_Path *, float x, float y) | Draws a line segment from the last point of a path to the target point. |
| OH_Drawing_PathClose (OH_Drawing_Path *) | Closes a path. A line segment from the start point to the last point of the path is added.|
| OH_Drawing_PenCreate (void) | Creates a pen object.|
| OH_Drawing_PenSetAntiAlias (OH_Drawing_Pen *, bool) | Checks whether anti-aliasing is enabled for a pen. If anti-aliasing is enabled, edges will be drawn with partial transparency.|
| OH_Drawing_PenSetWidth (OH_Drawing_Pen *, float width) | Sets the thickness for a pen. This thickness determines the width of the outline of a shape.|
| OH_Drawing_BrushCreate (void) | Creates a brush object.|
| OH_Drawing_BrushSetColor (OH_Drawing_Brush *, uint32_t color) | Sets the color for a brush. The color will be used by the brush to fill in a shape.|
| OH_Drawing_CreateTypographyStyle (void) | Creates a `TypographyStyle` object.|
| OH_Drawing_CreateTextStyle (void) | Creates a `TextStyle` object.|
| OH_Drawing_TypographyHandlerAddText (OH_Drawing_TypographyCreate *, const char *) | Sets the text content.|
| OH_Drawing_TypographyPaint (OH_Drawing_Typography *, OH_Drawing_Canvas *, double, double) | Paints text on the canvas.|
## Development Procedure for 2D Graphics Drawing
The following steps describe how to use the canvas and brush of the Native Drawing module to draw a 2D graphics.
1. **Create a bitmap object.** Use `OH_Drawing_BitmapCreate` in `drawing_bitmap.h` to create a bitmap object (named `cBitmap` in this example), and use `OH_Drawing_BitmapBuild` to specify its length, width, and pixel format.
```c++
// Create a bitmap object.
OH_Drawing_Bitmap* cBitmap = OH_Drawing_BitmapCreate();
// Define the pixel format of the bitmap.
OH_Drawing_BitmapFormat cFormat {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUYE};
// Set the pixel format for the bitmap.
OH_Drawing_BitmapBuild(cBitmap, width, height, &cFormat);
```
2. **Create a canvas object.** Use `OH_Drawing_CanvasCreate` in `drawing_canvas.h` to create a canvas object (named `cCanvas` in this example), and use `OH_Drawing_CanvasBind` to bind `cBitmap` to this canvas. The content drawn on the canvas will be output to the bound `cBitmap` object.
```c++
// Create a canvas object.
OH_Drawing_Canvas* cCanvas = OH_Drawing_CanvasCreate();
// Bind the bitmap to the canvas. The content drawn on the canvas will be output to the bound bitmap memory.
OH_Drawing_CanvasBind(cCanvas, cBitmap);
// Use white to clear the canvas.
OH_Drawing_CanvasClear(cCanvas, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0xFF, 0xFF));
```
3. **Construct a shape.** Use the APIs provided in `drawing_path.h` to draw a pentagram `cPath`.
```c++
int len = 300;
float aX = 500;
float aY = 500;
float dX = aX - len * std::sin(18.0f);
float dY = aY + len * std::cos(18.0f);
float cX = aX + len * std::sin(18.0f);
float cY = dY;
float bX = aX + (len / 2.0);
float bY = aY + std::sqrt((cX - dX) * (cX - dX) + (len / 2.0) * (len / 2.0));
float eX = aX - (len / 2.0);
float eY = bY;
// Create a path object and use the APIs to draw a pentagram.
OH_Drawing_Path* cPath = OH_Drawing_PathCreate();
// Specify the start point of the path.
OH_Drawing_PathMoveTo(cPath, aX, aY);
// Draw a line segment from the last point of a path to the target point.
OH_Drawing_PathLineTo(cPath, bX, bY);
OH_Drawing_PathLineTo(cPath, cX, cY);
OH_Drawing_PathLineTo(cPath, dX, dY);
OH_Drawing_PathLineTo(cPath, eX, eY);
// Close the path. Now the path is drawn.
OH_Drawing_PathClose(cPath);
```
4. **Set the brush and pen styles.** Use `OH_Drawing_PenCreate` in `drawing_pen.h` to create a pen (named `cPen` in this example), and set the attributes such as the anti-aliasing, color, and thickness. The pen is used to outline a shape. Use `OH_Drawing_BrushCreate` in `drawing_brush.h` to create a brush (named `cBrush` in this example), and set the brush color. The brush is used to fill in a shape. Use `OH_Drawing_CanvasAttachPen` and `OH_Drawing_CanvasAttachBrush` in `drawing_canvas.h` to attach the pen and brush to the canvas.
```c++
// Create a pen object and set the anti-aliasing, color, and thickness.
OH_Drawing_Pen* cPen = OH_Drawing_PenCreate();
OH_Drawing_PenSetAntiAlias(cPen, true);
OH_Drawing_PenSetColor(cPen, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0x00, 0x00));
OH_Drawing_PenSetWidth(cPen, 10.0);
OH_Drawing_PenSetJoin(cPen, LINE_ROUND_JOIN);
// Attach the pen to the canvas.
OH_Drawing_CanvasAttachPen(cCanvas, cPen);
// Create a brush object and set the color.
OH_Drawing_Brush* cBrush = OH_Drawing_BrushCreate();
OH_Drawing_BrushSetColor(cBrush, OH_Drawing_ColorSetArgb(0xFF, 0x00, 0xFF, 0x00));
// Attach the brush to the canvas.
OH_Drawing_CanvasAttachBrush(cCanvas, cBrush);
```
5. **Draw a shape.** Use `OH_Drawing_CanvasDrawPath` in `drawing_canvas.h` to draw a pentagram on the canvas. Call the corresponding APIs to destroy the objects when they are no longer needed.
```c++
// Draw a pentagram on the canvas. The outline of the pentagram is drawn by the pen, and the color is filled in by the brush.
OH_Drawing_CanvasDrawPath(cCanvas, cPath);
// Destroy the created objects when they are no longer needed.
OH_Drawing_BrushDestory(cBrush);
OH_Drawing_PenDestory(cPen);
OH_Drawing_PathDestory(cPath);
```
6. **Obtain pixel data.** Use `OH_Drawing_BitmapGetPixels` in `drawing_bitmap.h` to obtain the pixel address of the bitmap bound to the canvas. The memory to which the address points contains the pixel data of the drawing on the canvas.
```c++
// Obtain the pixel address after drawing. The memory to which the address points contains the pixel data of the drawing on the canvas.
void* bitmapAddr = OH_Drawing_BitmapGetPixels(cBitmap);
auto ret = memcpy_s(addr, addrSize, bitmapAddr, addrSize);
if (ret != EOK) {
LOGI("memcpy_s failed");
}
// Destroy the canvas object.
OH_Drawing_CanvasDestory(cCanvas);
// Destroy the bitmap object.
OH_Drawing_BitmapDestory(cBitmap);
```
## Development Procedure for Text Drawing and Display
The following steps describe how to use the text drawing and display feature of the Native Drawing module.
1. **Create a canvas and a bitmap.**
```c++
// Create a bitmap.
OH_Drawing_Bitmap* cBitmap = OH_Drawing_BitmapCreate();
OH_Drawing_BitmapFormat cFormat {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUE};
OH_Drawing_BitmapBuild(cBitmap, width, height, &cFormat);
// Create a canvas.
OH_Drawing_Canvas* cCanvas = OH_Drawing_CanvasCreate();
OH_Drawing_CanvasBind(cCanvas, cBitmap);
OH_Drawing_CanvasClear(cCanvas, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0xFF, 0xFF));
```
2. **Set the typography style.**
```c++
// Set the typography attributes such as left to right (LTR) for the text direction and left-aligned for the text alignment mode.
OH_Drawing_TypographyStyle* typoStyle = OH_Drawing_CreateTypographyStyle();
OH_Drawing_SetTypographyTextDirection(typoStyle, TEXT_DIRECTION_LTR);
OH_Drawing_SetTypographyTextAlign(typoStyle, TEXT_ALIGN_LEFT);
```
3. **Set the text style.**
```c++
// Set the text color, for example, black.
OH_Drawing_TextStyle* txtStyle = OH_Drawing_CreateTextStyle();
OH_Drawing_SetTextStyleColor(txtStyle, OH_Drawing_ColorSetArgb(0xFF, 0x00, 0x00, 0x00));
// Set text attributes such as the font size and weight.
double fontSize = 30;
OH_Drawing_SetTextStyleFontSize(txtStyle, fontSize);
OH_Drawing_SetTextStyleFontWeight(txtStyle, FONT_WEIGHT_400);
OH_Drawing_SetTextStyleBaseLine(txtStyle, TEXT_BASELINE_ALPHABETIC);
OH_Drawing_SetTextStyleFontHeight(txtStyle, 1);
// Set the font families.
const char* fontFamilies[] = {"Roboto"};
OH_Drawing_SetTextStyleFontFamilies(txtStyle, 1, fontFamilies);
OH_Drawing_SetTextStyleFontStyle(txtStyle, FONT_STYLE_NORMAL);
OH_Drawing_SetTextStyleLocale(txtStyle, "en");
```
4. **Generate the final text display effect.**
```c++
OH_Drawing_TypographyCreate* handler = OH_Drawing_CreateTypographyHandler(typoStyle,
OH_Drawing_CreateFontCollection());
OH_Drawing_TypographyHandlerPushTextStyle(handler, txtStyle);
// Set the text content.
const char* text = "OpenHarmony\n";
OH_Drawing_TypographyHandlerAddText(handler, text);
OH_Drawing_TypographyHandlerPopTextStyle(handler);
OH_Drawing_Typography* typography = OH_Drawing_CreateTypography(handler);
// Set the maximum width.
double maxWidth = 800.0;
OH_Drawing_TypographyLayout(typography, maxWidth);
// Set the start position for text display.
double position[2] = {10.0, 15.0};
OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]);
```
## Samples
The following samples are provided to help you better understand how to use the Native Drawing module:
* [2D Graphics Drawing Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/2d_graphics/drawing_c_sample.cpp)
* [Text Drawing and Painting Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/text/renderservice/drawing_text_c_sample.cpp)
# NativeWindow Development
## When to Use
`NativeWindow` is a local platform window of OpenHarmony. It provides APIs for you to create a native window from `Surface`, create a native window buffer from `SurfaceBuffer`, and request and flush a buffer.
The following scenarios are common for native window development:
* Drawing content using native C++ code and displaying the content on the screen
* Requesting and flushing a buffer when adapting to EGL `eglswapbuffer`
## Available APIs
| API| Description|
| -------- | -------- |
| OH_NativeWindow_CreateNativeWindowFromSurface (void \*pSurface) | Creates a `NativeWindow` instance. A new `NativeWindow` instance is created each time this function is called.|
| OH_NativeWindow_DestroyNativeWindow (struct NativeWindow \*window) | Decreases the reference count of a `NativeWindow` instance by 1 and, when the reference count reaches 0, destroys the instance.|
| OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer (void \*pSurfaceBuffer) | Creates a `NativeWindowBuffer` instance. A new `NativeWindowBuffer` instance is created each time this function is called.|
| OH_NativeWindow_DestroyNativeWindowBuffer (struct NativeWindowBuffer \*buffer) | Decreases the reference count of a `NativeWindowBuffer` instance by 1 and, when the reference count reaches 0, destroys the instance.|
| OH_NativeWindow_NativeWindowRequestBuffer (struct NativeWindow \*window struct NativeWindowBuffer \*\*buffer, int \*fenceFd) | Requests a `NativeWindowBuffer` through a `NativeWindow` instance for content production.|
| OH_NativeWindow_NativeWindowFlushBuffer (struct NativeWindow \*window, struct NativeWindowBuffer \*buffer, int fenceFd, Region region) | Flushes the `NativeWindowBuffer` filled with the content to the buffer queue through a `NativeWindow` instance for content consumption.|
| OH_NativeWindow_NativeWindowCancelBuffer (struct NativeWindow \*window, struct NativeWindowBuffer \*buffer) | Returns the `NativeWindowBuffer` to the buffer queue through a `NativeWindow` instance, without filling in any content. The `NativeWindowBuffer` can be used for another request.|
| OH_NativeWindow_NativeWindowHandleOpt (struct NativeWindow \*window, int code,...) | Sets or obtains the attributes of a native window, including the width, height, and content format.|
| OH_NativeWindow_GetBufferHandleFromNative (struct NativeWindowBuffer \*buffer) | Obtains the pointer to a `BufferHandle` of a `NativeWindowBuffer` instance.|
| OH_NativeWindow_NativeObjectReference (void \*obj) | Adds the reference count of a native object.|
| OH_NativeWindow_NativeObjectUnreference (void \*obj) | Decreases the reference count of a native object and, when the reference count reaches 0, destroys this object.|
| OH_NativeWindow_GetNativeObjectMagic (void \*obj) | Obtains the magic ID of a native object.|
## How to Develop
The following steps describe how to use `OH_NativeXComponent` in OpenHarmony to draw content using native C++ code and display the content on the screen.
1. Define an `XComponent` of the `texture` type in `index.ets` for content display.
```js
XComponent({ id: 'xcomponentId', type: 'texture', libraryname: 'nativerender'})
.borderColor(Color.Red)
.borderWidth(5)
.onLoad(() => {})
.onDestroy(() => {})
```
2. Obtain an `OH_NativeXComponent` instance (named `nativeXComponent` in this example) by calling `napi_get_named_property`, and obtain a `NativeWindow` instance by registering the callback of the `OH_NativeXComponent` instance.
```c++
// Define a NAPI instance.
napi_value exportInstance = nullptr;
// Define an OH_NativeXComponent instance.
OH_NativeXComponent *nativeXComponent = nullptr;
// Use the OH_NATIVE_XCOMPONENT_OBJ export instance.
napi_getname_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance);
// Convert the NAPI instance to the OH_NativeXComponent instance.
napi_unwarp(env, exportInstance, reinterpret_cast<void**>(&nativeXComponent));
```
3. Define the callback `OnSurfaceCreated`. During the creation of a `Surface`, the callback is used to initialize the rendering environment, for example, the `Skia` rendering environment, and write the content to be displayed to `NativeWindow`.
```c++
void OnSufaceCreatedCB(NativeXComponent* component, void* window) {
// Obtain the width and height of the native window.
uint64_t width_ = 0, height_ = 0;
OH_NativeXComponent_GetXComponentSize(nativeXComponent, window, &width_, &height_);
// Convert void* into a NativeWindow instance. NativeWindow is defined in native_window/external_window.h.
NativeWindow* nativeWindow_ = (NativeWindow*)(window);
// Set or obtain the NativeWindow attributes by calling OH_NativeWindow_NativeWindowHandleOpt.
// 1. Use SET_USAGE to set the usage attribute of the native window, for example, to HBM_USE_CPU_READ.
OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_USAGE, HBM_USE_CPU_READ | HBM_USE_CPU_WRITE |HBM_USE_MEM_DMA);
// 2. Use SET_BUFFER_GEOMETRY to set the width and height attributes of the native window.
OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_BUFFER_GEOMETRY, width_, height_);
// 3. Use SET_FORMAT to set the format attribute of the native window, for example, to PIXEL_FMT_RGBA_8888.
OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_FORMAT, PIXEL_FMT_RGBA_8888);
// 4. Use SET_STRIDE to set the stride attribute of the native window.
OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_STRIDE, 0x8);
// Obtain the NativeWindowBuffer instance by calling OH_NativeWindow_NativeWindowRequestBuffer.
struct NativeWindowBuffer* buffer = nullptr;
int fenceFd;
OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow_, &buffer, &fenceFd);
// Obtain the buffer handle by calling OH_NativeWindow_GetNativeBufferHandleFromNative.
BufferHandle* bufferHandle = OH_NativeWindow_GetNativeBufferHandleFromNative(buffer);
// Create a Skia bitmap using BufferHandle.
SkBitmap bitmap;
SkImageInfo imageInfo = ...
bitmap.setInfo(imageInfo, bufferHandle->stride);
bitmap.setPixels(bufferHandle->virAddr);
// Create Skia Canvas and write the content to the native window.
...
// After the write operation is complete, flush the buffer by using OH_NativeWindwo_NativeWindowFlushBuffer so that the data is displayed on the screen.
Regoin region{nullptr, 0};
OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow_, buffer, fenceFd, region)
}
```
4. Register the callback `OnSurfaceCreated` by using `OH_NativeXComponent_RegisterCallback`.
```c++
OH_NativeXComponent_Callback &callback_;
callback_->OnSurfaceCreated = OnSufaceCreatedCB;
callback_->OnSurfaceChanged = OnSufaceChangedCB;
callback_->OnSurfaceDestoryed = OnSufaceDestoryedCB;
callback_->DispatchTouchEvent = DispatchTouchEventCB;
OH_NativeXComponent_RegisterCallback(nativeXComponent, callback_)
```
此差异已折叠。
...@@ -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)
# 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.
先完成此消息的编辑!
想要评论请 注册