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

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

# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="PLATFORM" />
<option name="distributionType" value="LOCAL" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="C:\Program Files\Huawei\DevEco Studio 3.0.0.800\tools\gradle" />
<option name="gradleJvm" value="#JAVA_INTERNAL" />
<option name="resolveModulePerSourceSet" value="false" />
<option name="useQualifiedModuleNames" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/docs.iml" filepath="$PROJECT_DIR$/.idea/docs.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
\ No newline at end of file
......@@ -309,6 +309,8 @@ zh-cn/application-dev/reference/apis/js-apis-worker.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-xml.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-testRunner.md @HelloCrease
zh-cn/application-dev/reference/apis/js-apis-uitest.md @HelloCrease
zh-cn/application-dev/reference/apis/js-apis-hisysevent.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @zengyawen
zh-cn/application-dev/quick-start/start-overview.md @ge-yafang
zh-cn/application-dev/quick-start/start-with-ets.md @ge-yafang
zh-cn/application-dev/quick-start/start-with-ets-low-code.md @ge-yafang
......
......@@ -38,12 +38,13 @@
<!--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="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 name="copyrightPolicyFilter" desc="Filters for copyright header policies">
<!--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="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/-->
<filteritem type="filename" name="en/contribute" desc="already checked"/>
</filefilter>
<filefilter name="licenseFileNamePolicyFilter" desc="Filters for LICENSE file policies">
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
......@@ -65,7 +66,7 @@
<!--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="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>
</filefilterlist>
......
......@@ -6,6 +6,8 @@ This repository stores device and application development documents provided by
## Contents
[OpenAtom OpenHarmony](https://www.openharmony.cn/docs?navId=3&navName=OpenHarmony%20Documentation%20Overview)
[Chinese Documentation](zh-cn/readme.md)
[English Documentation](en/readme.md)
......
......@@ -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:
- 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\).
......@@ -42,42 +42,39 @@ This layer consists of system apps and third-party apps. Each OpenHarmony app is
## 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
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
- 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.
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.
- Resources can be scheduled based on the compatibility between user apps and the software platform.
- Adaptation of device capabilities \(including CPU, memory, peripheral, and software resources\) can be previewed.
- Resources can be scheduled based on the compatibility between 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>
......@@ -113,10 +110,10 @@ The following table describes the subsystems of OpenHarmony. For details about t
| 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 |
| DFileSystem | Provides APIs for synchronizing local JS files. | Standard system |
| Kernel| Supports small-sized LiteOS kernels that provide high performance and low power consumption for embedded devices and devices with limited resources, and supports Linux kernels that are applicable to the standard system.| Small system<br>Standard system |
| Distributed File System | Provides APIs for synchronizing local JS files. | Standard system |
| Graphics | Consists of user interface (UI) components, layout, animator, font, input event, window management, and rendering and drawing modules. It is an application framework that can be built on the LiteOS to develop OpenHarmony applications for Internet of Things (IoT) devices with limited hardware resources or on the standard OS to develop OpenHarmony applications for standard- and large-system devices (for example, tablet and lite smart devices). | All systems |
| Driver | Constructed using the C object-oriented programming (OOP) language. It provides a unified driver platform and is compatible with different kernels by means of platform decoupling and kernel decoupling. This unified driver platform is designed to provide a more precise and efficient development environment, where you develop a driver that can be deployed on different systems supporting Hardware Driver Foundation (HDF). | All systems |
| Driver | Constructed using the C object-oriented programming (OOP) language. It provides a unified driver platform and is compatible with different kernels by means of platform decoupling and kernel decoupling. This unified driver platform is designed to provide a more precise and efficient development environment, where you develop a driver that can be deployed on different systems supporting HDF. | All systems |
| Power Management | Provides the following functions: restarting the system, managing running locks, managing and querying the system power status, querying and reporting the charging and battery status, and turning on/off the device screen, including adjusting the screen brightness. | Standard system |
| Pan-sensor | Contains sensors and misc devices. A sensor is a device to detect events or changes in an environment and send messages about the events or changes to another electronic device. Misc devices, including vibrators and LED lights, are used to send signals externally. You can call APIs to control the vibration of vibrators and lighting-on and lighting-off of LED lights. | Small system |
| Multimodal Input | OpenHarmony provides a Natural User Interface (NUI) for you to interact with your users. Unlike conventional categorization of input methods, OpenHarmony combines input methods of different dimensions into multimodal inputs, so you can easily arm your app with multi-dimensional, natural interaction features by using the application framework and system built-in UI components or APIs. Specifically, OpenHarmony currently supports traditional input methods such as key and touch inputs. | Standard system |
......@@ -125,14 +122,14 @@ The following table describes the subsystems of OpenHarmony. For details about t
| Account | Provides interconnection with vendors' cloud account apps on the device side, and query and update of the cloud account login status. | Standard system |
| Compilation and Building | Provides a compilation and building framework based on Generate Ninja (GN) and Ninja. | All systems |
| Test | The test-driven development mode is used during the development process. You can develop new cases or modify existing cases to test new or enhanced system features. The test helps you develop high-quality code in the development phase. | All systems |
| Data Management | Provides local data management and distributed data management:<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 |
| Distributed Scheduler | Starts, registers, queries, and manages system services. | All systems |
| JS UI framework | OpenHarmony UI development framework that supports web-development-like paradigm. | All systems |
| Multimedia | Provides easy-to-use APIs for developing multimedia components such as audio, video, and camera, and enables apps to use multimedia resources of the system. | All systems |
| Event Notification | Provides the common event management capabilities that allow apps to subscribe to, unsubscribe from, publish, and receive common events (such as screen-on/off events and USB device attachment/detachment events). | Standard system |
| Common Event and Notification | Provides the common event management capabilities that allow apps to subscribe to, unsubscribe from, publish, and receive common events (such as screen-on/off events and USB device attachment/detachment events). | Standard system |
| Misc Services | Provides the function of setting the time. | Standard system |
| Bundle management | Provides bundle installation, uninstallation, update, and query capabilities. | All systems |
| Bundle management | Provides bundle installation, uninstall, update, and query capabilities. | All systems |
| Telephony | Provides basic communication capabilities of the cellular network, such as SIM cards, network search, cellular data, cellular calls, SMS, and MMS, as well as easy-to-use APIs for you to manage multiple types of calls and data network connections. | Standard system |
| Utils | Stores basic OpenHarmony components, which can be used by OpenHarmony subsystems and upper-layer apps. | All systems |
| Development Tools | Provides a performance profiler platform for you to analyze system issues such as memory and performance, including hdc used for device debugging, APIs for performance tracing, and a performance profiler framework. | Standard system |
......
......@@ -20,7 +20,6 @@
- Development
- [Ability Development](ability/Readme-EN.md)
- [UI Development](ui/Readme-EN.md)
- Basic Feature Development
- [Common Event and Notification](notification/Readme-EN.md)
- [Window Manager](windowmanager/Readme-EN.md)
- [WebGL](webgl/Readme-EN.md)
......@@ -29,9 +28,7 @@
- [Connectivity](connectivity/Readme-EN.md)
- [Data Management](database/Readme-EN.md)
- [Telephony](telephony/Readme-EN.md)
- [Agent-Powered Scheduled Reminders](background-agent-scheduled-reminder/Readme-EN.md)
- [Background Task Management](background-task-management/Readme-EN.md)
- [Work Scheduler](work-scheduler/Readme-EN.md)
- [Task Management](task-management/Readme-EN.md)
- [Device Management](device/Readme-EN.md)
- [Device Usage Statistics](device-usage-statistics/Readme-EN.md)
- [DFX](dfx/Readme-EN.md)
......@@ -47,7 +44,7 @@
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- APIs
- [JS (eTS Included) APIs](reference/apis/Readme-EN.md)
- [JS and TS APIs](reference/apis/Readme-EN.md)
- Native APIs
- [Standard Library](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md)
......
......@@ -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.
## Development Guidelines
The ability assistant is pre-installed in the device environment. You can directly invoke the tool using commands.
### Query-related Commands
## Query-related Commands
- **help**
......@@ -22,7 +18,7 @@ The ability assistant is pre-installed in the device environment. You can direct
aa help
```
### Ability-related Commands
## Ability-related Commands
- **start**
......@@ -69,18 +65,18 @@ The ability assistant is pre-installed in the device environment. You can direct
- **dump**
Prints ability-related information.
Prints ability related information.
| Name | Level-2 Parameter | Description |
| ----------------- | -------------------- | ------------------------------------------------------------ |
| -h/--help | - | Prints help information. |
| -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. |
| -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. |
| -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**
......
# 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.
- 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.
- 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.
- FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there are Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities.
- Stage model, which is introduced since API version 9. In the stage model, there are Ability and ExtensionAbility. The ExtensionAbility is further extended to ServiceExtensionAbility, FormExtensionAbility, DataShareExtensionAbility, and more.
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
| -------------- | ------------------------------------------------------------ | -------------------------------------------------------- |
| 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. |
| 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.|
| Intra-process object sharing| Not supported | Supported |
| 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). |
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).
## 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
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 2: Use the IDE.
- Method 1: Run the `aa test` command.
- Method 2: Use DevEco Studio.
### Running aa test
......@@ -37,16 +37,16 @@ aa test -b BundleName -m com.example.myapplicationfaets -s unittest OpenHarmonyT
| -s unittest | Yes | Name of the **TestRunner** to be used. The TestRunner name must be the same as the file name. |
| -w | No | Timeout interval of a test case, in seconds. If this parameter is not specified or is set to a value less than or equal to **0**, the test framework exits only after **finishTest** is invoked.|
| -s \<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. |
| -h | No | Help information. |
| -D | No | Debug mode for starting the tested application.|
| -h | No | Help information.|
### Using the IDE
### Using DevEco Studio
For details about how to use the IDE to start the test framework, see [IDE Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-openharmony-test-framework-0000001263160453#section1034420367508).
For details about how to use DevEco Studio to start the test framework, see [OpenHarmony Test Framework](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-openharmony-test-framework-0000001263160453#section1034420367508).
## Introduction to TestRunner
**TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and override the **onPrepare** and **onRun** APIs. When creating an application template, the IDE initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-testRunner.md).
**TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and override the **onPrepare** and **onRun** APIs. When creating an application template, DevEco Studio initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-testRunner.md).
## Introduction to AbilityDelegatorRegistry
......@@ -136,6 +136,7 @@ abilityDelegator.startAbility(want, (err, data) => {
### Running a Shell Command
**AbilityDelegator** provides APIs to run shell commands in the test environment.
**Example**
```javascript
......@@ -150,6 +151,7 @@ abilityDelegator.executeShellCommand(cmd, (err, data) => {
### Printing Log Information
**AbilityDelegator** provides APIs for printing log information. You can call any API in the test code to print process logs to the unit test console.
**Example**
```javascript
......@@ -165,6 +167,7 @@ abilityDelegator.print(msg, (err) => {
### Finishing the Test and Printing Log Information
**AbilityDelegator** provides the APIs for actively finishing the test. You can call any API in test code to finish the test and print logs to the unit test console.
**Example**
```javascript
......
......@@ -195,7 +195,7 @@ export default class MainAbility extends Ability {
### application/FormExtensionContext
For details, see [FormExtensionContext](/en/application-dev/reference/apis/js-apis-formextensioncontext.md).
For details, see [FormExtensionContext](../reference/apis/js-apis-formextensioncontext.md).
## Common Incorrect Usage
......
......@@ -3,22 +3,15 @@
## 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 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 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.
## 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
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.**
![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png)
......@@ -30,6 +23,20 @@ Currently, the **app.js** file provides only the **onCreate** and **onDestroy**
## 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)
## 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
## Available APIs
**Table 1** Data ability lifecycle callbacks
**Table 1** Data ability lifecycle APIs
|API|Description|
|:------|:------|
|onInitialized|Called during ability initialization to initialize the relational database (RDB).|
|update|Updates data in the database.|
|query|Queries data in the database.|
|delete|Deletes one or multiple data records from the database.|
|normalizeUri|Normalizes the URI. A normalized URI applies to cross-device use, persistence, backup, and restore. When the context changes, it ensures that the same data item can be referenced.|
|batchInsert|Inserts multiple data records into the database.|
|denormalizeUri|Converts a normalized URI generated by **normalizeUri** into a denormalized URI.|
|insert|Inserts a data record into the database.|
|openFile|Opens a file.|
|getFileTypes|Obtains the MIME type of a file.|
|getType|Obtains the MIME type matching the data specified by the URI.|
|executeBatch|Operates data in the database in batches.|
|call|A customized API.|
|onInitialized?(info: AbilityInfo): void|Called during ability initialization to initialize the relational database (RDB).|
|update?(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>): void|Updates data in the database.|
|query?(uri: string, columns: Array\<string>, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<ResultSet>): void|Queries data in the database.|
|delete?(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>): void|Deletes one or more data records from the database.|
|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?(uri: string, valueBuckets: Array\<rdb.ValuesBucket>, callback: AsyncCallback\<number>): void|Inserts multiple data records into the database.|
|denormalizeUri?(uri: string, callback: AsyncCallback\<string>): void|Converts a normalized URI generated by **normalizeUri** into a denormalized URI.|
|insert?(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback\<number>): void|Inserts a data record into the database.|
|openFile?(uri: string, mode: string, callback: AsyncCallback\<number>): void|Opens a file.|
|getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback\<Array\<string>>): void|Obtains the MIME type of a file.|
|getType?(uri: string, callback: AsyncCallback\<string>): void|Obtains the MIME type matching the data specified by the URI.|
|executeBatch?(ops: Array\<DataAbilityOperation>, callback: AsyncCallback\<Array\<DataAbilityResult>>): void|Operates data in the database in batches.|
|call?(method: string, arg: string, extras: PacMap, callback: AsyncCallback\<PacMap>): void|Calls a custom API.|
## How to Develop
### Creating a Data Ability
1. To meet the basic requirements of the database storage service, implement the **Insert**, **Query**, **Update**, and **Delete** APIs in the **Data** class to provide batch data processing. The traversal logic has been implemented by the **BatchInsert** and **ExecuteBatch** APIs.
1. To meet the basic requirements of the database storage service, implement the **Insert**, **Query**, **Update**, and **Delete** APIs in the **Data** class. The **BatchInsert** and **ExecuteBatch** APIs have already implemented the traversal logic, but not batch data processing.
The following code snippet shows how to create a Data ability:
```javascript
import dataAbility from '@ohos.data.dataAbility'
import dataRdb from '@ohos.data.rdb'
const TABLE_NAME = 'book'
const STORE_CONFIG = { name: 'book.db' }
const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, introduction TEXT NOT NULL)'
let rdbStore: dataRdb.RdbStore = undefined
export default {
onInitialized(abilityInfo) {
console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName)
......@@ -50,7 +58,7 @@ Data ability providers can customize data access-related APIs such as data inser
for (let i = 0;i < valueBuckets.length; i++) {
console.info('DataAbility batch insert i=' + i)
if (i < valueBuckets.length - 1) {
rdbStore.insert(TABLE_NAME, valueBuckets[i], (num: number) => {
rdbStore.insert(TABLE_NAME, valueBuckets[i], (err: any, num: number) => {
console.info('DataAbility batch insert ret=' + num)
})
} else {
......@@ -76,7 +84,7 @@ Data ability providers can customize data access-related APIs such as data inser
};
```
2. Submodule Configuration
2. Configure the submodule.
| JSON Field| Description |
| ------------ | ------------------------------------------------------------ |
......@@ -118,6 +126,10 @@ The basic dependency packages include:
For details about the APIs provided by **DataAbilityHelper**, see [DataAbilityHelper Module](../reference/apis/js-apis-dataAbilityHelper.md).
```js
// Different from the URI defined in the config.json file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/).
import featureAbility from '@ohos.ability.featureAbility'
import ohos_data_ability from '@ohos.data.dataAbility'
import ohos_data_rdb from '@ohos.data.rdb'
var urivar = "dataability:///com.ix.DataAbility"
var DAHelper = featureAbility.acquireDataAbilityHelper(
urivar
......@@ -137,7 +149,7 @@ The basic dependency packages include:
urivar,
valuesBucket,
(error, data) => {
expect(typeof(data)).assertEqual("number")
console.log("DAHelper insert result: " + data)
}
);
```
......@@ -156,7 +168,7 @@ The basic dependency packages include:
urivar,
da,
(error, data) => {
expect(typeof(data)).assertEqual("number")
console.log("DAHelper delete result: " + data)
}
);
```
......@@ -176,7 +188,7 @@ The basic dependency packages include:
valuesBucket,
da,
(error, data) => {
expect(typeof(data)).assertEqual("number")
console.log("DAHelper update result: " + data)
}
);
```
......@@ -197,7 +209,7 @@ The basic dependency packages include:
valArray,
da,
(error, data) => {
expect(typeof(data)).assertEqual("object")
console.log("DAHelper query result: " + data)
}
);
```
......@@ -217,7 +229,7 @@ The basic dependency packages include:
urivar,
cars,
(error, data) => {
expect(typeof(data)).assertEqual("number")
console.log("DAHelper batchInsert result: " + data)
}
);
```
......@@ -241,12 +253,12 @@ The basic dependency packages include:
valuesBucket: {"executeBatch" : "value1",},
predicates: da,
expectedCount:0,
PredicatesBackReferences: {},
predicatesBackReferences: null,
interrupted:true,
}
],
(error, data) => {
expect(typeof(data)).assertEqual("object")
console.log("DAHelper executeBatch result: " + data)
}
);
```
......@@ -265,21 +277,15 @@ The basic dependency packages include:
},
predicates: da,
expectedCount:0,
PredicatesBackReferences: {},
predicatesBackReferences: null,
interrupted:true,
}
]
);
```
## Development Example
The following sample is provided to help you better understand how to develop a Data ability:
- [DataAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/DataAbility)
This sample shows how to:
## Samples
Create a Data ability in the **data.ts** file in the **DataAbility** directory.
The following sample is provided to help you better understand how to develop Data abilities:
Encapsulate the process of accessing the Data ability in the **MainAbility** directory.
- [`DataAbility`: Creation and Access of Data Abilities (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DataAbility)
......@@ -3,20 +3,12 @@
## Widget Overview
A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application.
A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive features such as opening a UI page or sending a message. The widget host is responsible for displaying the widget.
A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message.
Basic concepts:
- Widget provider
The widget provider is an atomic service that provides the content to be displayed. It controls the display content, component layout, and component click events of a widget.
- Widget host
The widget host is an application that displays the widget content and controls the position where the widget is displayed in the host application.
- Widget Manager
The Widget Manager is a resident agent that manages widgets added to the system and provides functions such as periodic widget update.
- Widget provider: an atomic service that controls what and how content is displayed in a widget and interacts with users.
- Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application.
- Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<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.
......@@ -30,7 +22,7 @@ The widget provider controls the widget content to display, component layout, an
Form ability development refers to the development conducted by the widget provider based on the [Feature Ability (FA) model](fa-brief.md). As a widget provider, you need to carry out the following operations:
- Develop the lifecycle callbacks in **LifecycleForm**.
- Create a **FormBindingData** object.
- Create a **FormBindingData** instance.
- Update a widget through **FormProvider**.
- Develop the widget UI page.
......@@ -46,9 +38,9 @@ The table below describes the lifecycle callbacks provided **LifecycleForm**.
| onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.|
| onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. |
| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change of widget visibility. |
| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process the widget event. |
| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event. |
| onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. |
| onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a specified widget. |
| onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a widget. |
For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md).
......@@ -81,7 +73,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li
export default {
onCreate(want) {
console.log('FormAbility onCreate');
// Persistently store widget information for subsequent use, such as widget instance retrieval and update.
// Persistently store widget information for subsequent use, such as during widget instance retrieval or update.
let obj = {
"title": "titleOnCreate",
"detail": "detailOnCreate"
......@@ -94,7 +86,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li
console.log('FormAbility onCastToNormal');
},
onUpdate(formId) {
// To support scheduled update, periodic update, or update requested by the widget host for a widget, override this method for data update.
// To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update.
console.log('FormAbility onUpdate');
let obj = {
"title": "titleOnUpdate",
......@@ -124,11 +116,11 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li
}
```
### Configuring config.json for the Form Ability
### Configuring the Widget Configuration File
Configure the **config.json** file for the **Form** ability.
Configure the **config.json** file for the widget.
- The **js** module in the **config.json** file provides the JavaScript resources of the **Form** ability. The internal field structure is described as follows:
- The **js** module in the **config.json** file provides the JavaScript resources of the widget. The internal field structure is described as follows:
| Field| Description | Data Type| Default |
| -------- | ------------------------------------------------------------ | -------- | ------------------------ |
......@@ -161,12 +153,12 @@ Configure the **config.json** file for the **Form** ability.
| isDefault | Whether the widget is a default one. Each ability has only one default widget.<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 |
| 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 |
| 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**) |
| 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) |
| jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. | String | No |
| metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) |
......@@ -203,7 +195,7 @@ Configure the **config.json** file for the **Form** ability.
```
### Widget Data Persistence
### Persistently Store Widget Data
Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget.
......@@ -215,6 +207,7 @@ Mostly, the widget provider is started only when it needs to obtain information
let formName = want.parameters["ohos.extra.param.key.form_name"];
let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"];
// Persistently store widget information for subsequent use, such as widget instance retrieval and update.
// The storeFormInfo API is not implemented here. For details about the implementation, see "FA Model Widget" provided in "Samples".
storeFormInfo(formId, formName, tempFlag, want);
let obj = {
......@@ -230,9 +223,11 @@ You should override **onDestroy** to delete widget data.
```javascript
onDestroy(formId) {
// Delete widget data.
deleteFormInfo(formId);
console.log('FormAbility onDestroy');
// You need to implement the code for deleting the persistent widget 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
Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one.
Normal widget: a widget that will be persistently used by the widget host
- Normal widget: a widget that will be persistently used by the widget host
Temporary widget: a widget that is temporarily used by the widget host
- Temporary widget: a widget that is temporarily used by the widget host
Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget host may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets.
### Developing the Widget UI Page
You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<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.
- HML:
......@@ -331,10 +326,8 @@ Now you've got a widget shown below.
![fa-form-example](figures/fa-form-example.png)
## Development Example
The following sample is provided to help you better understand how to develop a widget on the FA model:
[FormAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility)
## Samples
This sample provides a widget. Users can create, update, and delete widgets on the home screen of their devices or by using their own widget host. This sample also implements widget information persistence by using lightweight data storage.
The following samples are provided to help you better understand how to develop a widget on the FA model:
- [`FormAbility`: FA Model Widget (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility)
- [`FormLauncher`: Widget Host (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormLauncher)
......@@ -155,8 +155,7 @@ In the cross-device scenario, the application must also apply for the data synch
for (let i = 0;i < array.length; i++) {
let result = await atManager.verifyAccessToken(tokenID, array[i]);
console.info("verifyAccessToken result:" + JSON.stringify(result));
if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
} else {
if (result != abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
requestPermissions.push(array[i]);
}
}
......
......@@ -5,22 +5,20 @@ A Service ability is used to run tasks in the background, such as playing music
## Available APIs
**Table 1** Service ability lifecycle callbacks
**Table 1** Service ability lifecycle APIs
|API|Description|
|:------|:------|
|onStart|Called to initialize a Service ability when the Service ability is being created. This callback is invoked only once in the entire lifecycle of a Service ability. The **Want** object passed to this callback must be null.|
|onCommand|Called every time a Service ability is created on a client. You can calculate calling statistics and perform initialization operations in this callback.|
|onConnect|Called when another ability is connected to the Service ability.|
|onDisconnect|Called when another ability is disconnected from the Service ability.|
|onStop|Called when the Service ability is being destroyed. You should override this callback for your Service ability to clear its resources, such as threads and registered listeners.|
|onStart?(): void|Called to initialize a Service ability being created. This callback is invoked only once in the entire lifecycle of a Service ability. The **Want** object passed to this callback must be null.|
|onCommand?(want: Want, startId: number): void|Called every time a Service ability is created on a client. You can collect calling statistics and perform initialization operations in this callback.|
|onConnect?(want: Want): rpc.RemoteObject|Called when another ability is connected to the Service ability.|
|onDisconnect?(want: Want): void|Called when another ability is disconnected from the Service ability.|
|onStop?(): void|Called when the Service ability is being destroyed. You should override this callback for your Service ability to clear its resources, such as threads and registered listeners.|
## How to Develop
### Creating a Service Ability
### Creating and Registering a Service Ability
1. Create a child class of the **Ability** class and override the following Service ability-related lifecycle callbacks to implement your own logic for processing requests to interact with your Service ability:
The following code snippet shows how to create a Service ability:
1. Override the Service ability-related lifecycle callbacks to implement your own logic for processing interaction requests.
```javascript
export default {
......@@ -32,6 +30,7 @@ A Service ability is used to run tasks in the background, such as playing music
},
onConnect(want) {
console.log('ServiceAbility OnConnect');
return null;
},
onDisconnect(want) {
console.log('ServiceAbility OnDisConnect');
......@@ -44,7 +43,7 @@ A Service ability is used to run tasks in the background, such as playing music
2. Register a Service ability.
You must declare your Service ability in the **config.json** file by setting its **type** attribute to **service**.
Declare the Service ability in the **config.json** file by setting its **type** attribute to **service**.
```javascript
{
......@@ -78,12 +77,12 @@ The following code snippet shows how to start a Service ability running on the l
```javascript
import featureAbility from '@ohos.ability.featureAbility';
let promise = await featureAbility.startAbility(
let promise = featureAbility.startAbility(
{
want:
{
bundleName: "com.jstest.serviceability",
abilityName: "com.jstest.serviceability.MainAbility",
bundleName: "com.jstest.service",
abilityName: "com.jstest.service.ServiceAbility",
},
}
);
......@@ -93,11 +92,26 @@ After the preceding code is executed, the **startAbility()** API is called to st
- If the Service ability is not running, the system calls **onStart()** to initialize the Service ability, and then calls **onCommand()** on the Service ability.
- If the Service ability is running, the system directly calls **onCommand()** on the Service ability.
The following code snippet shows how to start a Service ability running on the remote device. For details about **getRemoteDeviceId()**, see [Connecting to a Remote Service Ability](#connecting-to-a-remote-service-ability-applying-only-to-system-applications).
```javascript
import featureAbility from '@ohos.ability.featureAbility';
let promise = featureAbility.startAbility(
{
want:
{
deviceId: getRemoteDeviceId(), // Remote device ID
bundleName: "com.jstest.service",
abilityName: "com.jstest.service.ServiceAbility",
},
}
);
```
### Stopping a Service Ability
Once created, the Service ability keeps running in the background. The system does not stop or destroy it unless memory resources must be reclaimed. You can call **terminateSelf()** on a Service ability to stop it.
Once created, the Service ability keeps running in the background. The system does not stop or destroy it unless memory resources must be reclaimed.
......@@ -105,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()**.
When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails.
The following code snippet shows how to implement the callbacks:
You can use either of the following methods to connect to a Service ability:
```javascript
let mRemote;
function onConnectCallback(element, remote){
1. Using the IDL to automatically generate code
Use OpenHarmony Interface Definition Language (IDL) to automatically generate the corresponding client, server, and **IRemoteObject** code. For details, see [“Development Using TS” in OpenHarmony IDL Specifications and User Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/IDL/idl-guidelines.md#development-using-ts).
2. Writing code in the corresponding file
When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails.
The following code snippet shows how to implement the callbacks:
```javascript
import prompt from '@system.prompt'
let mRemote;
function onConnectCallback(element, remote){
console.log('onConnectLocalService onConnectDone element: ' + element);
console.log('onConnectLocalService onConnectDone remote: ' + remote);
mRemote = remote;
......@@ -137,43 +162,43 @@ function onConnectCallback(element, remote){
console.log('sendRequest error:' + e);
});
}
}
function onDisconnectCallback(element){
function onDisconnectCallback(element){
console.log('ConnectAbility onDisconnect Callback')
}
}
function onFailedCallback(code){
function onFailedCallback(code){
console.log('ConnectAbility onFailed Callback')
}
```
}
```
The following code snippet shows how to connect to a local Service ability:
The following code snippet shows how to connect to a local Service ability:
```javascript
import featureAbility from '@ohos.ability.featureAbility';
let connId = featureAbility.connectAbility(
```javascript
import featureAbility from '@ohos.ability.featureAbility';
let connId = featureAbility.connectAbility(
{
bundleName: "com.jstest.serviceability",
abilityName: "com.jstest.serviceability.MainAbility",
bundleName: "com.jstest.service",
abilityName: "com.jstest.service.ServiceAbility",
},
{
onConnect: onConnectCallback,
onDisconnect: onDisconnectCallback,
onFailed: onFailedCallback,
},
);
```
);
```
When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of the **IRemoteObject** interface. You can inherit **rpc.RemoteObject** to implement your own class of **IRemoteObject**.
When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of **IRemoteObject**. You can extend **rpc.RemoteObject** to implement your own class of **IRemoteObject**.
The following code snippet shows how the Service ability instance returns itself to the calling ability:
The following code snippet shows how the Service ability instance returns itself to the calling ability:
```javascript
import rpc from "@ohos.rpc";
```javascript
import rpc from "@ohos.rpc";
let mMyStub;
export default {
let mMyStub;
export default {
onStart() {
class MyStub extends rpc.RemoteObject{
constructor(des) {
......@@ -210,19 +235,24 @@ export default {
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: The **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. Therefore, remote Service ability startup applies only to system applications.
>**NOTE**
>
>This feature applies only to system applications, since the **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications.
If you need to connect a Service ability to a Page ability on another device or to a Service ability in another application on another device, you must first implement the **IAbilityConnection** interface for the connection. A Service ability allows other abilities on another device to connect to it through **connectAbility()**.
If you need to connect a Service ability to a Page ability or another Service ability on a remote device, you must first implement the **IAbilityConnection** interface for the connection. A Service ability allows abilities on another device to connect to it through **connectAbility()**.
When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails.
The following code snippet shows how to implement the callbacks:
```ts
import prompt from '@system.prompt'
let mRemote;
function onConnectCallback(element, remote){
console.log('onConnectRemoteService onConnectDone element: ' + element);
......@@ -264,7 +294,10 @@ The **Want** of the target Service ability must contain the remote **deviceId**,
```ts
import deviceManager from '@ohos.distributedHardware.deviceManager';
// For details about the implementation of dmClass, see the implementation in Distributed Demo in Samples.
let dmClass;
function getRemoteDeviceId() {
if (typeof dmClass === 'object' && dmClass != null) {
let list = dmClass.getTrustedDeviceListSync();
......@@ -327,15 +360,12 @@ async function RequestPermission() {
let context = featureAbility.getContext();
context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{
console.info("data:" + JSON.stringify(data));
console.info("data requestCode:" + data.requestCode);
console.info("data permissions:" + data.permissions);
console.info("data authResults:" + data.authResults);
});
console.info('RequestPermission end');
}
```
When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of the **IRemoteObject** interface. You can inherit **rpc.RemoteObject** to implement your own class of **IRemoteObject**.
When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of **IRemoteObject**. You can extend **rpc.RemoteObject** to implement your own class of **IRemoteObject**.
The following code snippet shows how the Service ability instance returns itself to the calling ability:
......@@ -398,5 +428,5 @@ export default {
## Samples
The following samples are provided to help you better understand how to develop a Service ability:
- [`ServiceAbility`: Service Ability Creation and Use (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceAbility)
- [`DMS`: Distributed Demo (eTS) (API7)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS)
- [`ServiceAbility`: Service Ability Creation and Use (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceAbility)
- [`DMS`: Distributed Demo (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS)
......@@ -2,19 +2,18 @@
## When to Use
Ability continuation is to continue the current mission of an application, including the UI component status variables and distributed objects, on another device. The UI component status variables are used to synchronize page data, and the distributed objects are used to synchronize data in the memory.
Ability continuation is to continue the current mission of an application, including the UI component state variables and distributed objects, on another device. The UI component state variables are used to synchronize UI data, and the distributed objects are used to synchronize memory data.
## Available APIs
The following table lists the APIs used for ability continuation. For details about the APIs, see [Ability](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-application-ability.md).
The following table lists the APIs used for ability continuation. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md).
**Table 1** Ability continuation APIs
|API| Description|
|:------ | :------|
| onContinue(wantParam : {[key: string]: any}): OnContinueResult | Called by the **initiator** to save data during the ability continuation preparation process. The return value **0** means that the continuation request is accepted, and an error code means that the continuation request is denied.|
| onCreate(want: Want, param: LaunchParam): void| Called by the **target** to restore the data and page.|
| **enum** OnContinueResult | Enumerates the return values of **onContinue**. The options are as follows: **AGREE** (request accepted), **REJECT** (request denied), and **MISMATCH** (version mismatch).|
| onContinue(wantParam : {[key: string]: any}): OnContinueResult | Called by the initiator to store the data required for continuation and request continuation. The value **AGREE** means that the continuation is accepted, and **REJECT** means the continuation is rejected, and **MISMATCH** means a version mismatch.|
| onCreate(want: Want, param : LaunchParam): void | Called by the target to restore the data and UI page.|
......@@ -22,6 +21,8 @@ The following table lists the APIs used for ability continuation. For details ab
![continuation_dev](figures/continuation-info.png)
In effect, ability continuation is a cross-device ability startup that carries data. When the continuation is triggered, device A calls back **onContinue()** of the application. You must save the current data in this API. Then, device A initiates a cross-device ability startup on device B and transmits the data to device B. Device B calls back **onCreate()**. You must restore the transmitted data in this API.
## How to Develop
### Application Continuation
......@@ -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
"launchType": "standard"
......@@ -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.
......@@ -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:
```javascript
......@@ -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:
......@@ -111,15 +118,14 @@ The following table lists the APIs used for ability continuation. For details ab
import AbilityConstant from '@ohos.application.AbilityConstant';
```
- To implement ability continuation, you must implement this API and have the value **AGREE** returned.
To implement ability continuation, you must implement this API and have the value **AGREE** returned.
- Example
Example
```javascript
onContinue(wantParam : {[key: string]: any}) {
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');
Logger.info(`onContinue input = ${wantParam["input"]}`);
return AbilityConstant.OnContinueResult.AGREE
......@@ -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
onCreate(want, launchParam) {
Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
globalThis.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
let input = want.parameters.input // get user data from want params
let input = want.parameters.input // Obtain user data from want params.
AppStorage.SetOrCreate<string>('ContinueInput', input)
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
### 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
import Ability from '@ohos.application.Ability';
......@@ -187,10 +191,11 @@ The following table lists the APIs used for ability continuation. For details ab
wantParam["session"] = this.sessionId;
return AbilityConstant.OnContinueResult.AGREE
}
```
- The target device obtains the session ID from **onCreate**, creates a distributed object, and associates the distributed object with the session ID. In this way, the distributed object can be synchronized. Before calling **restoreWindowStage**, ensure that all distributed objects required for continuation have been associated for correct data retrieval.
- The target device obtains the session ID from **onCreate()**, creates a distributed object, and associates the distributed object with the session ID. In this way, the distributed object can be synchronized. Before calling **restoreWindowStage**, ensure that all distributed objects required for continuation have been associated.
```javascript
import Ability from '@ohos.application.Ability';
......@@ -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
### Design Ideas
## Design Ideas
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.
![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**
......@@ -20,10 +20,10 @@ The stage model is designed based on the following considerations:
- **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.
......@@ -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.
- **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.
- **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.
- **Ability**: provides lifecycle callback, holds the **AbilityContext** class, and supports component continuation and collaboration.
- **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**: 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**.
- **WindowStage**: local window manager.
- **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)
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:
......@@ -62,11 +62,11 @@ Abilities can be started in any of the following modes:
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)
### 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:
......@@ -82,9 +82,9 @@ The following figure uses the widget scenario as an example. You can inherit fro
![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.
......
......@@ -18,11 +18,11 @@ The table below describes the ability call APIs. For details, see [Ability](../r
**Table 1** Ability call APIs
|API|Description|
|:------|:------|
|startAbilityByCall(want: Want): Promise<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.|
|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.|
|callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessageParcel>|Sends agreed sequenceable data to the callee and returns the agreed sequenceable data.|
|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.|
|release(): void|Releases the caller interface.|
|onRelease(callback: OnReleaseCallBack): void|Registers a callback that is invoked when the caller is disconnected.|
......@@ -83,7 +83,7 @@ export default class MySequenceable {
```
4. Implement **Callee.on** and **Callee.off**.
The time to register a listener for the callee depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **CalleeSortMethod** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code snippet is as follows:
The time to register a listener for the callee depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code snippet is as follows:
```ts
const TAG: string = '[CalleeAbility]'
const MSG_SEND_METHOD: string = 'CallSendMsg'
......@@ -148,7 +148,7 @@ async onButtonGetCaller() {
console.error(TAG + 'get caller failed with ' + error)
})
```
In the cross-device scenario, you need to specify the ID of the peer device. The sample code snippet is as follows:
In the cross-device scenario, you need to specify the ID of the peer device. The sample code snippet is as follows:
```ts
let TAG = '[MainAbility] '
var caller = undefined
......@@ -172,7 +172,7 @@ context.startAbilityByCall({
console.error(TAG + 'get remote caller failed with ' + error)
})
```
Obtain the ID of the peer device from **DeviceManager**. Note that the **getTrustedDeviceListSync** API is open only to system applications. The sample code snippet is as follows:
Obtain the ID of the peer device from **DeviceManager**. Note that the **getTrustedDeviceListSync** API is open only to system applications. The sample code snippet is as follows:
```ts
import deviceManager from '@ohos.distributedHardware.deviceManager';
var dmClass;
......@@ -190,7 +190,7 @@ function getRemoteDeviceId() {
}
}
```
In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code snippet is as follows:
In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code snippet is as follows:
```ts
let context = this.context
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC']
......@@ -215,7 +215,7 @@ async onButtonCall() {
}
```
In the following, **CallWithResult** is used to send data **originMsg** to the callee and assign the data processed by the **CallSendMsg** method to **backMsg**. The sample code snippet is as follows:
In the following, **CallWithResult** is used to send data **originMsg** to the callee and assign the data processed by the **CallSendMsg** method to **backMsg**. The sample code snippet is as follows:
```ts
const MSG_SEND_METHOD: string = 'CallSendMsg'
originMsg: string = ''
......
# Service Extension Ability Development
## When to Use
**ExtensionAbility** is the base class of the new **Extension** component in the stage model. It is used to process jobs without UIs. The lifecycle of an Extension ability is simple, and it does not involve foreground or background. **ServiceExtensionAbility** is extended from **ExtensionAbility**.
**ExtensionAbility** is the base class of the new Extension component in the stage model. It is used to process missions without UIs. The lifecycle of an Extension ability is simple, and it does not involve foreground or background. **ServiceExtensionAbility** is extended from **ExtensionAbility**.
You can customize a class that inherits from **ServiceExtensionAbility** and override the lifecycle callbacks of **ServiceExtensionAbility** to perform service logic operations during the initialization, connection, and disconnection processes.
You can customize a class that inherits from **ServiceExtensionAbility** and override the lifecycle callbacks in the base class to perform service logic operations during the initialization, connection, and disconnection processes.
## Available APIs
......@@ -19,7 +19,7 @@ You can customize a class that inherits from **ServiceExtensionAbility** and ove
## Constraints
- Currently, OpenHarmony does not support creation of a **ServiceExtensionAbility** for third-party applications.
- Currently, OpenHarmony does not support creation of a Service Extension ability for third-party applications.
## How to Develop
......@@ -82,4 +82,5 @@ The following sample is provided to help you better understand how to develop a
- [ServiceExtensionAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceExtAbility)
This sample will guide you through creating a Service Extension ability in the **ServiceExtAbility.ts** file in the **ServiceExtensionAbility** directory.
\ No newline at end of file
This sample shows how to create a Service Extension ability in the **ServiceExtAbility.ts** file in the **ServiceExtensionAbility** directory.
# WantAgent Development
## When to Use
The **WantAgent** class encapsulates want information that specifies a particular action, which can be starting an ability or publishing a common event. You can either call **wantAgent.trigger** to trigger a **WantAgent** directly or add a **WantAgent** to a notification so that it will be triggered when users tap the notification.
### Introduction
The **WantAgent** class encapsulates a **Want** object that specifies a particular action. You can trigger a **WantAgent** by calling **wantAgent.trigger** directly or by adding it to a notification so that it is triggered when a user taps the notification.
You can use a **WantAgent** in a notification to start an ability or publish a common event.
### When to Use
Start another ability through a **WantAgent**.
### Available APIs
## Available APIs
| API | Description|
| ---------------------------------------------------------------------------------------------- | ----------- |
| wantAgent.getWantAgentInfo(info: WantAgentInfo, callback: AsyncCallback\<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.|
| commonEvent.trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback\<CompleteData\>) | Triggers a **WantAgent**.|
| getWantAgentInfo(info: WantAgentInfo, callback: AsyncCallback\<WantAgent\>) | Creates a **WantAgent** object. This API uses an asynchronous callback to return the result.|
| getWantAgent(info: WantAgentInfo): Promise\<WantAgent\> | Creates a **WantAgent** object. This API uses a promise to return the result.|
| trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback\<CompleteData\>) | Triggers a **WantAgent** object.|
### How to Develop
## How to Develop
1. Import the **WantAgent** module.
```javascript
import wantAgent from '@ohos.wantAgent';
```
```
import wantAgent from '@ohos.wantAgent';
```
2. Create a **WantAgentInfo** object. 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
var wantAgentInfo = {
//wantAgentInfo
var wantAgentInfo = {
wants: [
{
deviceId: "",
......@@ -40,34 +34,53 @@ var wantAgentInfo = {
parameters: {}
}
],
operationType: OperationType.START_ABILITY,
operationType: wantAgent.OperationType.START_ABILITY,
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.
wantAgent.getWantAgent(wantAgentInfo, (err, wantAgentObj) => {
```
private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations.
//wantAgentInfo
var wantAgentInfo = {
wants: [
{
action: "event_name", // Set the action name.
parameters: {}
}
],
operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
requestCode: 0,
wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
}
```
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) {
console.error("[WantAgent]getWantAgent err=" + JSON.stringify(err))
} else {
console.log("[WantAgent]getWantAgent success")
this.wantAgentObj = wantAgentObj
}
})
```
})
```
4. Trigger the **WantAgent**.
5. Trigger the **WantAgent** object.
```
// Trigger the WantAgent.
var triggerInfo = {
```
// Trigger the WantAgent object.
var triggerInfo = {
code:0
}
wantAgent.trigger(wantAgentObj, triggerInfo, (completeData) => {
}
wantAgent.trigger(wantAgentObj, triggerInfo, (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
All applications should be developed on top of these frameworks.
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)
- [WebGL](webgl/Readme-EN.md)
- [Media](media/Readme-EN.md)
- [Security](security/Readme-EN.md)
- [Connectivity](connectivity/Readme-EN.md)
- [Telephony](telephony/Readme-EN.md)
- [Data Management](database/Readme-EN.md)
- [Agent-Powered Scheduled Reminders](background-agent-scheduled-reminder/Readme-EN.md)
- [Background Task Management](background-task-management/Readme-EN.md)
- [Task Management](task-management/Readme-EN.md)
- [Device Management](device/Readme-EN.md)
- [Device Usage Statistics](device-usage-statistics/Readme-EN.md)
- [DFX](dfx/Readme-EN.md)
- [Internationalization](internationalization/Readme-EN.md)
- [IDL Specifications and User Guide](IDL/idl-guidelines.md)
- [Using Native APIs in Application Projects](napi/Readme-EN.md)
### Tools
......@@ -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 (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- APIs
- [JS (eTS Included) APIs](reference/apis/Readme-EN.md)
- [JS and TS APIs](reference/apis/Readme-EN.md)
- Native APIs
- [Standard Library](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md)
......
......@@ -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.
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)
- [WebGL](webgl/webgl-overview.md)
- [Media](media/audio-overview.md)
- [Security](security/userauth-overview.md)
- [Connectivity](connectivity/ipc-rpc-overview.md)
- [Telephony](telephony/telephony-overview.md)
- [Data Management](database/database-mdds-overview.md)
- [Agent-Powered Scheduled Reminders](background-agent-scheduled-reminder/background-agent-scheduled-reminder-overview.md)
- [Background Task Management](background-task-management/background-task-overview.md)
- [Task Management](task-management/background-task-overview.md)
- [Device](device/usb-overview.md)
- [Device Usage Statistics](device-usage-statistics/device-usage-statistics-overview.md)
- [DFX](dfx/hiappevent-overview.md)
- [Internationalization](internationalization/international-overview.md)
- [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md)
- [Using Native APIs in Application Projects](napi/napi-guidelines.md)
### Tools
......@@ -51,6 +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.
They are organized as follows:
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/js-components-common-attributes.md)
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/ts-universal-events-click.md)
- [API Reference](reference/apis/js-apis-DataUriUtils.md)
- [JS and TS APIs](reference/apis/js-apis-DataUriUtils.md)
- Native APIs
- [Standard Library](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md)
# 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
```
// Register the TestAbilityStub instance with the SystemAbilityManager on the same device as the SA.
auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
samgr->AddSystemAbility(said, new TestAbility());
samgr->AddSystemAbility(saId, new TestAbility());
// Register the TestAbilityStub instance with the SystemAbilityManager on a different device.
auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
ISystemAbilityManager::SAExtraProp saExtra;
saExtra.isDistributed = true; // Set a distributed SA.
int result = samgr->AddSystemAbility(said, new TestAbility(), saExtra);
int result = samgr->AddSystemAbility(saId, new TestAbility(), saExtra);
```
6. Obtain the SA.
......@@ -149,12 +149,12 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat
```
// Obtain the proxy of the SA registered on the local device.
sptr<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.
// Obtain the proxies of the SAs registered with other devices.
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.
```
......
......@@ -13,62 +13,107 @@ Call **createDistributedObject()** to create a distributed data object instance.
**Table 1** API for creating a distributed data object instance
| 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. |
| 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.|
### 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.
**Table 2** API for generating a session ID randomly
| 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. |
| 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.|
### 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.
**Table 3** API for setting a session ID
| 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. |
| Class| API| Description|
| -------- | -------- | -------- |
| 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
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
| Class | API | Description |
| -------- | -------- | -------- |
| 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. |
| Class| API| Description|
| -------- | -------- | -------- |
| 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. **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
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
| 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 | off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' \ | 'offline' }>): void | Unsubscribes from status changes of a distributed data object. |
| 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| 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
The following example shows how to implement a distributed data object synchronization.
1. Import the @ohos.data.distributedDataObject module to the development environment.
```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
var local_object = distributedObject.createDistributedObject({name:undefined, age:undefined, isVis:true,
parent:undefined, list:undefined});
......@@ -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
// Local object
......@@ -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.
```
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
function changeCallback(sessionId, changeData) {
......@@ -108,8 +157,9 @@ The following example shows how to implement a distributed data object synchroni
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
local_object.name = "jack";
local_object.age = 19;
......@@ -127,23 +177,23 @@ The following example shows how to implement a distributed data object synchroni
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
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
// Unsubscribe from the specified data change callback.
// Unregister the specified data change callback.
local_object.off("change", changeCallback);
// Unsubscribe from all data change callbacks.
// Unregister all data change callbacks.
local_object.off("change");
```
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.
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.
The sample code is as follows:
```js
function statusCallback(sessionId, networkId, status) {
this.response += "status changed " + sessionId + " " + status + " " + networkId;
......@@ -152,22 +202,59 @@ The following example shows how to implement a distributed data object synchroni
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
// Unsubscribe from the specified status change callback.
local_object.off("status", statusCallback);
// Unsubscribe from all status change callbacks.
local_object.off("status");
// Save a distributed data object.
local_object.save("local", (result, data)=>{
console.log("save callback");
console.info("save sessionId " + data.sessionId);
console.info("save version " + data.version);
console.info("save deviceId " + data.deviceId);
});
// Revoke the data saving operation.
local_object.revokeSave((result, data) =>{
console.log("revokeSave callback");
console.info("revokeSave sessionId " + data.sessionId);
});
```
- Promise
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
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:
......@@ -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.
......@@ -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
- **The application usage statistics can include the following**:
1. Events of all applications based on the specified start time and end time
2. Application usage duration statistics based on the specified start time and end time
3. Events of the current application based on the specified start time and end time
4. Application usage duration statistics in the specified time frame at the specified interval (daily, weekly, monthly, or annually)
5. Priority group of the current invoker application
6. Whether a specific application is in the idle state
7. Number of FA usage records specified by **maxNum**, sorted by time (most recent first). If **maxNum** is not specified, the default value **1000** will be used.
8. Number of notifications from applications based on the specified start time and end time
9. Statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time
9. Priority group of the invoker application or a specified application
- **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
- The **queryBundleActiveStates**, **queryBundleStateInfos**, and **queryBundleStateInfoByInterval** APIs used for device usage statistics are system APIs. Before calling these APIs, you need to apply for the **ohos.permission.BUNDLE_ACTIVE_INFO** permission.
- This permission is not required for calling **queryCurrentBundleActiveStates**, **queryAppUsagePriorityGroup**, and **isIdleState**, which are third-party APIs.
- Before calling the following system APIs, you need to apply for the **ohos.permission.BUNDLE_ACTIVE_INFO** permission: **queryBundleActiveStates**, **queryBundleStateInfos**, **queryBundleStateInfoByInterval**, **queryBundleActiveEventStates**, **queryAppNotificationNumber**, **queryAppUsagePriorityGroup(bundleName?)**, **setBundleGroup**, **registerGroupCallBack**, and **unRegisterGroupCallBack**.
- This permission is not required for calling third-party APIs: **queryCurrentBundleActiveStates**, **queryAppUsagePriorityGroup()**, and **isIdleState**.
# 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.
## 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 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
<a name="table948mcpsimp"></a>
<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>
<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>
</th>
</tr>
</thead>
<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>
</td>
<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>
</td>
</tr>
<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>
</td>
<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>
</td>
</tr>
<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>
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| hasRight(deviceName: string): boolean | Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise. |
| requestRight(deviceName: string): Promise\<boolean> | Requests the temporary permission for a given application to access the USB device. |
| connectDevice(device: USBDevice): Readonly\<USBDevicePipe> | Connects to the USB device based on the device information returned by **getDevices()**. |
| getDevices(): Array<Readonly\<USBDevice>> | Obtains the USB device list. |
| setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. |
| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. |
| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface |
| function bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise\<number> | Performs bulk transfer. |
| closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. |
| releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. |
| getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. |
| getRawDescriptor(pipe: USBDevicePipe): Uint8Array | Obtains the raw USB descriptor. |
| controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise\<number> | Performs control transfer. |
## How to Develop
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
usb.releaseInterface(pipe, interface);
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
## Available APIs
| 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;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.|
| 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;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;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;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;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. |
## How to Develop
......
......@@ -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): 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**
......@@ -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. |
## 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
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
The HiAppEvent module of OpenHarmony can be used to develop application event services and provide functions related to application events, including flushing application events to a disk and querying historical application event data.
**Logging**: Logs changes caused by user operations to provide service data for development, product, and O&M analysis.
## Event Verification Result Codes
| Result Code | Cause | Check Rule | Processing Method |
| ----------- | ---------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| 0 | None | Event verification is successful. | Event logging is normal. No action is required. |
| -1 | Invalid event name | The event name is not empty and contains a maximum of 48 characters.<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
---
## ***Note***:
1. This document applies to JavaScript.
---
## **Summary**
This guide will show how a JS application can use AudioCapturer to record the audio.
Applications can use the APIs provided in this document to record raw audio files.
## **AudioCapturer Framework**
The AudioCapturer interface is one of the most important components of the audio framework.
### **Audio Capturing:**
The AudioCapturer framework provides APIs for capturing raw audio files.
## **Usage**
Here's an example of how to use AudioCapturer to capture a raw audio file.
1. Use **createAudioCapturer()** to create an AudioCapturer instance. Capturer parameters can be set in **audioCapturerOptions**.\
This instance can be used to record, control, and obtain the recording status, as well as to register a callback for notifications.
```
## When to Use
You can use the APIs provided by **AudioCapturer** to record raw audio files.
### State Check
During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioCapturer** instance. This is because some operations can be performed only when the audio capturer is in a given state. If the application performs an operation when the audio capturer is not in the given state, the system may throw an exception or generate other undefined behavior.
For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md).
**Figure 1** Audio capturer state
![](figures/audio-capturer-state.png)
## How to Develop
1. Use **createAudioCapturer()** to create an **AudioCapturer** instance.
Set parameters of the **AudioCapturer** instance in **audioCapturerOptions**. This instance is used to capture audio, control and obtain the recording status, and register a callback for notification.
```js
var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1,
......@@ -39,10 +42,10 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
var state = audioRenderer.state;
```
2. (Optional) Subscribe to audio capturer state change events using the **on('stateChange')** API.
If an application wants to take some action based on the state updates in capturer, the application can subscribe to the state change event.
There are more events that applications can subscribe to, such as 'markReach' and 'periodReach'. Refer to [Audio](../reference/apis/js-apis-audio.md) for more details.
```
2. (Optional) Use **on('stateChange')** to subscribe to audio renderer state changes.
If an application needs to perform some operations when the audio renderer state is updated, the application can subscribe to the state changes. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md).
```js
audioCapturer.on('stateChange',(state) => {
console.info('AudioCapturerLog: Changed State to : ' + state)
switch (state) {
......@@ -68,31 +71,33 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
break;
}
});
```
3. Call the **start()** function on the AudioCapturer instance to start/resume the recording task.\
The capturer state will be STATE_RUNNING once the start is complete. The application can then begin reading buffers.
```
3. Use **start()** to start audio recording.
The capturer state will be **STATE_RUNNING** once the audio capturer is started. The application can then begin reading buffers.
```js
await audioCapturer.start();
if (audioCapturer.state == audio.AudioState.STATE_RUNNING) {
console.info('AudioRecLog: Capturer started');
} else {
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();
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
until the application wants to stop the recording. The following example shows how to write recorded data into a file.
```
5. Read the captured audio data and convert it to a byte stream. Call **read()** repeatedly to read the data until the application wants to stop the recording.
The following example shows how to write recorded data into a file.
```js
import fileio from '@ohos.fileio';
const path = '/data/data/.pulse_dir/capture_js.wav';
......@@ -123,7 +128,9 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
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();
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.
}
```
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();
if (audioCapturer.state == audio.AudioState.STATE_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.
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.
>![](../public_sys-resources/icon-note.gif) **NOTE**
>Due to permission issues, the above features are temporarily unavailable for the standard system.
## Basic Concepts<a name="section296512102281"></a>
## Basic Concepts
- **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 rate**
Sampling rate is the number of samples extracted from a continuous signal per second to form a discrete signal. It is measured in Hz. Generally, human hearing range is from 20 Hz to 20 kHz. Common audio sampling rates include 8 kHz, 11.025 kHz, 22.05 kHz, 16 kHz, 37.8 kHz, 44.1 kHz, 48 kHz, 96 kHz, and 192 kHz.
- **Channel**
Channels refer to different spatial positions where independent audio signals are recorded or played. The number of channels is the number of audio sources used during audio recording, or the number of speakers used for audio playback.
- **Audio frame**
Audio data is in stream form. For the convenience of audio algorithm processing and transmission, it is generally agreed that a data amount in a unit of 2.5 to 60 milliseconds is one audio frame. This unit is called sampling time, and its length is specific to codecs and the application requirements.
- **PCM**
Pulse code modulation \(PCM\) is a method used to digitally represent sampled analog signals. It converts continuous-time analog signals into discrete-time digital signal samples.
- **PCM**<br>
Pulse code modulation (PCM) is a method used to digitally represent sampled analog signals. It converts continuous-time analog signals into discrete-time digital signal samples.
......@@ -256,7 +256,8 @@ export class AudioDemo {
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)
- [<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)
- [<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)
- [`JsDistributedMusicPlayer`: Distributed Music Player (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/ability/JsDistributedMusicPlayer)
- [`JsAudioPlayer`: Audio Playback and Management (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer)
- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
......@@ -190,7 +190,8 @@ export class AudioRecorderDemo {
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)
- [<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)
- [<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)
- [`Recorder`: Recorder (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder)
- [`JsRecorder`: Recorder (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/JSRecorder)
- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
# Audio Rendering Development
---
## ***Note***:
1. This document applies to JavaScript.
---
## **Summary**
This guide will show you how to use AudioRenderer to create an audio player app.
You can use the APIs provided in this document to play audio files in output devices and manage playback tasks.
## **AudioRenderer Framework**
The AudioRenderer interface is one of the most important components of the audio framework.
### **Audio Rendering:**
The AudioRenderer framework provides APIs for playing audio files and controlling the playback.
### **Audio Interruption:**
When a higher priority stream wants to play, the AudioRenderer framework interrupts the lower priority stream.\
For example, if a call is arrived when you listen to music, the music playback, which is the lower priority stream, is paused.\
With the sample code below, we'll look at how AudioInterrupt works in detail.\
<br/>
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.
## **Usage**
Here's an example of how to use AudioRenderer to play a raw audio file.
1. Use **createAudioRenderer** to create an AudioRenderer instance. Renderer parameters can be set in **audioRendererOptions**.\
This object can be used to play, control, and obtain the status of the playback, as well as receive callback notifications.
```
## When to Use
**AudioRenderer** provides APIs for rendering audio files and controlling playback. It also supports audio interruption. You can use the APIs provided by **AudioRenderer** to play audio files in output devices and manage playback tasks.
### Audio Interruption
When an audio stream with a higher priority needs to be played, the audio renderer interrupts the stream with a lower priority. For example, if a call comes in when the user is listening to music, the music playback, which is the lower priority stream, is paused. For details, see [How to Develop](#how-to-develop).
### State Check
During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioRenderer** instance. This is because some operations can be performed only when the audio renderer is in a given state. If the application performs an operation when the audio renderer is not in the given state, the system may throw an exception or generate other undefined behavior.
**Figure 1** Audio renderer state
![](figures/audio-renderer-state.png)
### Asynchronous Operations
To ensure that the UI thread is not blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8).
## How to Develop
1. Use **createAudioRenderer()** to create an **AudioRenderer** instance.
Set parameters of the audio renderer in **audioCapturerOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification.
```js
var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1,
......@@ -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);
```
2. Subscribe to audio interruption events using the **on** API.\
Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device.\
In some cases, the framework takes forced actions like pausing and ducking, and notifies the app using **InterruptEvent**. In other cases, the app can take action. In this situation, the app can choose to act on the **InterruptEvent** or ignore it. When the app is interrupted by forced action, it should handle the state, update the user interface, and so on.
In case of audio interrupts, the app may encounter write failures. Interrupt unaware apps can check the renderer state using the **audioRenderer.state** API before writing audio data, whereas interrupt aware apps will have more details accessible via this listener.\
<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.
2. Use **on('interrupt')** to subscribe to audio interruption events.
| Value | Description |
| :-------------------- | :--------------------------- |
| INTERRUPT_HINT_PAUSE | Pausing the playback. |
| INTERRUPT_HINT_RESUME | Resuming the playback. |
| INTERRUPT_HINT_STOP | Stopping the playback. |
| INTERRUPT_HINT_DUCK | Ducking the stream volume. |
| INTERRUPT_HINT_UNDUCK | Unducking the stream volume. |
Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device.
4) **Some actions are exclusively forced or shared**, which means that they are performed by either the framework or the app.\
For instance, when a call is received while a music stream is ongoing, the framework forces the music stream to pause. When the call is finished, the framework will not forcibly resume the music stream. Instead, it will alert the app to resume the playback.
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.
| Action | Description |
| :-------------------- | :-------------------------------------------------------------------------------- |
| INTERRUPT_HINT_RESUME | INTERRUPT_SHARE is always the forceType. It can only be done by the app. |
| INTERRUPT_HINT_DUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. |
| INTERRUPT_HINT_UNDUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. |
In the case of audio interruption, the application may encounter write failures. To avoid such failures, interruption unaware applications can use **audioRenderer.state** to check the renderer state before writing audio data. The applications can obtain more details by subscribing to the audio interruption events. For details, see [InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9).
```
```js
audioRenderer.on('interrupt', (interruptEvent) => {
console.info('InterruptEvent Received');
console.info('InterruptType: ' + interruptEvent.eventType);
......@@ -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.\
The renderer state will be STATE_RUNNING once the start is complete. You can then begin writing buffers.
```
3. Use **start()** to start audio rendering.
The renderer state will be **STATE_RUNNING** once the audio renderer is started. The application can then begin reading buffers.
```js
async function startRenderer() {
var state = audioRenderer.state;
// state should be prepared, paused or stopped.
// The state should be prepared, paused, or stopped.
if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED ||
state != audio.AudioState.STATE_STOPPED) {
console.info('Renderer is not in a correct state to start');
......@@ -154,11 +124,13 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
console.error('Renderer start failed');
}
}
```
5. Make **write** calls to start rendering the buffers.
Read the audio data to be played into a buffer. Call the write function repeatedly to write data.
```
4. Call **write()** to write data to the buffer.
Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer.
```js
async function writeBuffer(buf) {
var state = audioRenderer.state;
if (state != audio.AudioState.STATE_RUNNING) {
......@@ -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
```
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() {
var state = audioRenderer.state;
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.
} else {
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.\
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()**.
```
```js
async function releaseRenderer() {
if (state_ == RELEASED || state_ == NEW) {
console.info('Resourced already released');
......@@ -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) => {
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('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // Obtain the camera position.
console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type.
console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // Obtain the camera connection type.
}
}
// Create a camera input stream.
let cameraInput
await cameraManager.createCameraInput(cameraArray[0].cameraId).then((input) => {
// Create a camera input stream.
let cameraInput
await cameraManager.createCameraInput(cameraArray[0].cameraId).then((input) => {
console.log('Promise returned with the CameraInput instance');
cameraInput = input
})
......
......@@ -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)
**Figure 2** Layer 0 diagram of video playback
![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.
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,
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).
*Note: **setSurface** must be called after the URL is set but before **prepare** is called.
For details about how to create an XComponent, see [XComponent](../reference/arkui-ts/ts-basic-components-xcomponent.md).
```js
import media from '@ohos.multimedia.media'
......@@ -120,7 +116,7 @@ export class VideoPlayerDemo {
console.info('pause success');
}, 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;
await videoPlayer.getTrackDescription().then((arrlist) => {
if (typeof (arrlist) != 'undefined') {
......
# Native APIs
- [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_)
```
# Raw File Development
## When to Use
This document describes how to use the native Rawfile APIs to manage raw file directories and files in OpenHarmony. You can use the APIs to traverse, open, search for, read, and close raw files.
## Available APIs
| API | Description |
| :----------------------------------------------------------- | :--------------------------------------- |
| NativeResourceManager *OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr) | Initializes the native resource manager. |
| RawDir *OH_ResourceManager_OpenRawDir(const NativeResourceManager *mgr, const char *dirName) | Opens a raw file directory. |
| int OH_ResourceManager_GetRawFileCount(RawDir *rawDir) | Obtains the number of raw files in the specified directory.|
| const char *OH_ResourceManager_GetRawFileName(RawDir *rawDir, int index) | Obtains the name of a raw file. |
| RawFile *OH_ResourceManager_OpenRawFile(const NativeResourceManager *mgr, const char *fileName) | Opens a raw file. |
| long OH_ResourceManager_GetRawFileSize(RawFile *rawFile) | Obtains the size of a raw file. |
| int OH_ResourceManager_SeekRawFile(const RawFile *rawFile, long offset, int whence) | Seeks a read/write position in a raw file based on the specified offset. |
| long OH_ResourceManager_GetRawFileOffset(const RawFile *rawFile) | Obtains the offset. |
| int OH_ResourceManager_ReadRawFile(const RawFile *rawFile, void *buf, size_t length) | Reads a raw file. |
| void OH_ResourceManager_CloseRawFile(RawFile *rawFile) | Closes a raw file to release resources. |
| void OH_ResourceManager_CloseRawDir(RawDir *rawDir) | Closes a raw file directory to release resources. |
| bool OH_ResourceManager_GetRawFileDescriptor(const RawFile *rawFile, RawFileDescriptor &descriptor) | Obtains the file descriptor (FD) of a raw file. |
| bool OH_ResourceManager_ReleaseRawFileDescriptor(const RawFileDescriptor &descriptor) | Releases the FD of a raw file. |
| void OH_ResourceManager_ReleaseNativeResourceManager(NativeResourceManager *resMgr) | Releases the native resource manager. |
## How to Develop
1. Add the header file.
```c++
#include "raw_file_manager.h"
```
2. Call **OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr)** to obtain a **NativeResourceManager** instance.
```js
// Import the JS resource manager from the JS head file and pass it to the C++ file.
import resManager from '@ohos.resourceManager'
import rawfileTest from 'librawFileTest.so'
resManager.getResourceManager().then(resmgr => {
rawfileTest.testRawFile("test", resmgr, (error, value) => {
console.log("test rawFile");
})
});
```
```c++
// Obtain and parse the parameters in the C++ file.
NativeResourceManager* nativeResourceManager = nullptr;
std::string path;
if (i == 0 && valueType == napi_string) {
// Parse the first parameter, which is the file or directory path relative to the raw file directory.
......
path = buf.data();
} else if (i == 1 && valueType == napi_object) {
// Parse the second parameter, which is the JS resource manager.
nativeResourceManager = OH_ResourceManager_InitNativeResourceManager(env, argv[i]);
}
```
3. Call **OH_ResourceManager_OpenRawDir** to obtain a **RawDir** instance based on the **NativeResourceManager** instance.
```c++
RawDir* rawDir = OH_ResourceManager_OpenRawDir(nativeResourceManager, path.c_str());
```
4. Call **OH_ResourceManager_GetRawFileCount** to obtain the total number of raw files in the directory based on the **RawDir** instance.
```c++
int count = OH_ResourceManager_GetRawFileCount(rawDir);
```
5. Call **OH_ResourceManager_GetRawFileName** to obtain the name of the raw file with the specified index.
```c++
for (int index = 0; index < count; index++) {
std::string fileName = OH_ResourceManager_GetRawFileName(rawDir, index);
}
```
6. Call **OH_ResourceManager_OpenRawFile** to obtain a **RawFile** instance with the specified file name.
```c++
RawFile* rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, fileName.c_str());
```
7. Call **OH_ResourceManager_GetRawFileSize** to obtain the size of the raw file.
```c++
long rawFileSize = OH_ResourceManager_GetRawFileSize(rawFile);
```
8. Call **OH_ResourceManager_SeekRawFile** to seek a read/write position in the raw file based on the specified offset.
```c++
int position = OH_ResourceManager_SeekRawFile(rawFile, 10, 0);
int position = OH_ResourceManager_SeekRawFile(rawFile, 0 , 1);
int position = OH_ResourceManager_SeekRawFile(rawFile, -10, 2);
```
9. Call **OH_ResourceManager_GetRawFileOffset** to obtain the raw file offset.
```c++
long rawFileOffset = OH_ResourceManager_GetRawFileOffset(rawFile)
```
10. Call **OH_ResourceManager_ReadRawFile** to read the raw file.
```c++
std::unique_ptr<char[]> mediaData = std::make_unique<char[]>(rawFileSize);
long rawFileOffset = OH_ResourceManager_ReadRawFile(rawFile, mediaData.get(), rawFileSize);
```
11. Call **OH_ResourceManager_CloseRawFile** to close the file to release resources.
```c++
OH_ResourceManager_CloseRawFile(rawFile);
```
12. Call **OH_ResourceManager_CloseRawDir** to close the raw file directory.
```c++
OH_ResourceManager_CloseRawDir(rawDir);
```
13. Call **OH_ResourceManager_GetRawFileDescriptor** to obtain the FD of the raw file.
```c++
RawFileDescriptor descriptor;
bool result = OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor);
```
14. Call **OH_ResourceManager_ReleaseRawFileDescriptor** to release the FD of the raw file.
```c++
OH_ResourceManager_ReleaseRawFileDescriptor(descriptor);
```
15. Call **OH_ResourceManager_ReleaseNativeResourceManager** to release the native resource manager.
```c++
OH_ResourceManager_ReleaseNativeResourceManager(nativeResourceManager);
```
......@@ -2,5 +2,8 @@
- [Common Event and Notification Overview](notification-brief.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)
......@@ -2,9 +2,9 @@
The common event and notification module provides debugging tools to facilitate your application development. With these tools, you can view common event and notification information, publish common events, and more. These tools have been integrated with the system. You can run related commands directly in the shell.
### cem Debugging Assistant
## cem Debugging Assistant
##### publish
### publish
* Functionality
......@@ -41,7 +41,7 @@ The common event and notification module provides debugging tools to facilitate
![cem-publish-all](figures/cem-publish-all.png)
##### dump
### dump
* Functionality
......@@ -67,7 +67,7 @@ The common event and notification module provides debugging tools to facilitate
​ ![cem-dump-e](figures/cem-dump-e.png)
##### help
### help
* Functionality
......@@ -83,9 +83,9 @@ The common event and notification module provides debugging tools to facilitate
### anm Debugging Assistant
## anm Debugging Assistant
##### dump
### dump
* Functionality
......@@ -119,7 +119,7 @@ The common event and notification module provides debugging tools to facilitate
Set the number of the cached recent notifications to be displayed to 10.
##### help
### help
* Functionality
......
# 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.
# Common Event Development
### Introduction
## Introduction
OpenHarmony provides a Common Event Service (CES) for applications to subscribe to, publish, and unsubscribe from common events.
Common events are classified into system common events and custom common events.
......@@ -25,13 +25,13 @@ You can create a subscriber object to subscribe to a common event to obtain the
### How to Develop
1. Import the **commonEvent** module.
```javascript
```js
import commonEvent from '@ohos.commonEvent';
```
2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo).
```javascript
```js
private subscriber = null // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information
......@@ -42,7 +42,7 @@ var subscribeInfo = {
3. Create a subscriber object and save the returned object for subsequent operations such as subscription and unsubscription.
```javascript
```js
// Callback for subscriber creation.
commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => {
if (err.code) {
......@@ -57,7 +57,7 @@ commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => {
4. Create a subscription callback, which is triggered when an event is received. The data returned by the subscription callback contains information such as the common event name and data carried by the publisher. For details about the data types and parameters of the common event data, see [CommonEventData](../reference/apis/js-apis-commonEvent.md#commoneventdata).
```javascript
```js
// Callback for common event subscription.
if (this.subscriber != null) {
commonEvent.subscribe(this.subscriber, (err, data) => {
......@@ -74,7 +74,7 @@ if (this.subscriber != null) {
}
```
## Public Event Publishing Development
## Common Event Publishing Development
### When to Use
You can use the **publish** APIs to publish a custom common event, which can carry data for subscribers to parse and process.
......@@ -89,13 +89,13 @@ You can use the **publish** APIs to publish a custom common event, which can car
#### Development for Publishing a Common Event
1. Import the **commonEvent** module.
```javascript
```js
import commonEvent from '@ohos.commonEvent';
```
2. Pass in the common event name and callback, and publish the event.
```javascript
```js
// Publish a common event.
commonEvent.publish("event", (err) => {
if (err.code) {
......@@ -109,13 +109,13 @@ commonEvent.publish("event", (err) => {
#### Development for Publishing a Common Event with Given Attributes
1. Import the **commonEvent** module.
```javascript
```js
import commonEvent from '@ohos.commonEvent'
```
2. Define attributes of the common event to publish. For details about the data types and parameters in the data to publish, see [CommonEventPublishData](../reference/apis/js-apis-commonEvent.md#commoneventpublishdata).
```javascript
```js
// Attributes of a common event.
var options = {
code: 1, // Result code of the common event
......@@ -125,7 +125,7 @@ var options = {
3. Pass in the common event name, attributes of the common event, and callback, and publish the event.
```javascript
```js
// Publish a common event.
commonEvent.publish("event", options, (err) => {
if (err.code) {
......@@ -149,14 +149,14 @@ You can use the **unsubscribe** API to unsubscribe from a common event.
### How to Develop
1. Import the **commonEvent** module.
```javascript
```js
import commonEvent from '@ohos.commonEvent';
```
2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#Common-Event-Subscription-Development).
3. Invoke the **unsubscribe** API in **CommonEvent** to unsubscribe from the common event.
```javascript
```js
if (this.subscriber != null) {
commonEvent.unsubscribe(this.subscriber, (err) => {
if (err.code) {
......
......@@ -109,7 +109,7 @@ Open the index.visual file, right-click the existing template components on the
## Implementing Page Redirection
You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URI. Import the **router** module and then perform the steps below:
You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URL. Import the **router** module and then perform the steps below:
1. Implement redirection from the first page to the second page.
......
# DataUriUtils Module
> **NOTE**<br/>
> **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......
# MissionSnapshot
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......@@ -10,7 +9,7 @@ Provides the snapshot of a mission.
## Modules to Import
```
import abilitymanager from '@ohos.application.abilityManager';
import missionManager from '@ohos.application.missionManager'
import ElementName from '@ohos.bundle';
import image from '@ohos.multimedia.image';
```
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册