提交 fcfb2e21 编写于 作者: F fangyun

update

Signed-off-by: Nfangyun <fangyun2@huawei.com>

要显示的变更太多。

To preserve performance only 1001 of 1001+ files are displayed.
此差异已折叠。
...@@ -18,15 +18,15 @@ This repository stores device and application development documents provided by ...@@ -18,15 +18,15 @@ This repository stores device and application development documents provided by
- master: the latest version. - master: the latest version.
- OpenHarmony 3.2 Beta1. [Learn more](en/release-notes/OpenHarmony-v3.2-beta1.md) - OpenHarmony 3.2 Beta3. [Learn more](en/release-notes/OpenHarmony-v3.2-beta3.md)
- OpenHarmony 3.1 Release. [Learn more](en/release-notes/OpenHarmony-v3.1-release.md) - OpenHarmony 3.1 Release. [Learn more](en/release-notes/OpenHarmony-v3.1-release.md)
This version is upgraded to OpenHarmony 3.1.1 LTS. [Learn more](en/release-notes/OpenHarmony-v3.1.1-release.md) This version is upgraded to OpenHarmony 3.1.3 Release. [Learn more](en/release-notes/OpenHarmony-v3.1.3-release.md)
- OpenHarmony 3.0 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0-LTS.md) - OpenHarmony 3.0 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0-LTS.md)
This version is upgraded to OpenHarmony 3.0.5 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0.5-LTS.md) This version is upgraded to OpenHarmony 3.0.6 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0.6-LTS.md)
- OpenHarmony 2.2 Beta2. [Learn more](en/release-notes/OpenHarmony-v2.2-beta2.md) - OpenHarmony 2.2 Beta2. [Learn more](en/release-notes/OpenHarmony-v2.2-beta2.md)
...@@ -34,14 +34,14 @@ This repository stores device and application development documents provided by ...@@ -34,14 +34,14 @@ This repository stores device and application development documents provided by
### Historical Stable Versions ### Historical Stable Versions
OpenHarmony_v1.x_release: OpenHarmony v1.1.4 LTS. [Learn more](en/release-notes/OpenHarmony-v1-1-4-LTS.md) OpenHarmony_v1.x_release: OpenHarmony v1.1.5 LTS. [Learn more](en/release-notes/OpenHarmony-v1.1.5-LTS.md)
[More versions](en/release-notes/) [More versions](en/release-notes/)
## Third-Party Open-Source Software and License Notice ## Third-Party Open-Source Software and License Notice
Third-party license: [Third-Party Open-Source Software and License Notice](en/contribute/third-party-open-source-software-and-license-notice.md) Third-party license: [Third-Party Open-Source Software and License Notice](en/contribute/open-source-software-and-license-notice.md)
## Contribution ## Contribution
......
...@@ -146,7 +146,7 @@ The following table describes the subsystems of OpenHarmony. For details about t ...@@ -146,7 +146,7 @@ The following table describes the subsystems of OpenHarmony. For details about t
## Supported Development Boards ## Supported Development Boards
Currently, the OpenHarmony community supports 17 types of development boards, which are listed in [Development Boards Supported](device-dev/dev-board-on-the-master.md). The following table describes three of them, which are the first three integrated into the OpenHarmony master. You can visit http://ci.openharmony.cn/dailys/dailybuilds to obtain daily builds. Currently, the OpenHarmony community supports 22 types of development boards, which are listed in [Development Boards Supported](device-dev/dev-board-on-the-master.md). The following table describes three of them, which are the first three integrated into the OpenHarmony master. You can visit http://ci.openharmony.cn/dailys/dailybuilds to obtain daily builds.
| System Type| Board Model| Chip Model| <div style="width:200pt">Function Description and Use Case</div> | Application Scenario| Code Repository | | System Type| Board Model| Chip Model| <div style="width:200pt">Function Description and Use Case</div> | Application Scenario| Code Repository |
| -------- | -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- | -------- |
...@@ -156,11 +156,9 @@ Currently, the OpenHarmony community supports 17 types of development boards, wh ...@@ -156,11 +156,9 @@ Currently, the OpenHarmony community supports 17 types of development boards, wh
## Getting Started ## Getting Started
- [Getting Started for Device Development](device-dev/quick-start/quickstart-ide-lite-overview.md) - [Getting Started for Device Development](device-dev/quick-start/quickstart-overview.md)
- [Getting Started for Application Development](application-dev/quick-start/start-overview.md) - [Getting Started for Application Development](application-dev/quick-start/start-overview.md)
## Code Repository Addresses ## Code Repository Addresses
OpenHarmony project: [https://gitee.com/openharmony](https://gitee.com/openharmony) OpenHarmony project: [https://gitee.com/openharmony](https://gitee.com/openharmony)
...@@ -173,6 +171,8 @@ OpenHarmony archived projects: [https://gitee.com/openharmony-retired](https://g ...@@ -173,6 +171,8 @@ OpenHarmony archived projects: [https://gitee.com/openharmony-retired](https://g
## OpenHarmony Documentation ## OpenHarmony Documentation
[Official website](https://www.openharmony.cn/)
[Chinese version](https://gitee.com/openharmony/docs/tree/master/zh-cn) [Chinese version](https://gitee.com/openharmony/docs/tree/master/zh-cn)
[English version](https://gitee.com/openharmony/docs/tree/master/en) [English version](https://gitee.com/openharmony/docs/tree/master/en)
...@@ -197,7 +197,7 @@ For details about how to contribute, see [How to contribute](contribute/how-to-c ...@@ -197,7 +197,7 @@ For details about how to contribute, see [How to contribute](contribute/how-to-c
OpenHarmony complies with Apache License Version 2.0. For details, see the LICENSE in each repository. OpenHarmony complies with Apache License Version 2.0. For details, see the LICENSE in each repository.
OpenHarmony uses third-party open-source software and licenses. For details, see [Third-Party Open-Source Software](https://gitee.com/openharmony/docs/blob/master/en/contribute/third-party-open-source-software-and-license-notice.md). OpenHarmony uses third-party open-source software and licenses. For details, see [Open Source Software and License Notice](https://gitee.com/openharmony/docs/blob/master/en/contribute/open-source-software-and-license-notice.md).
## Contact Info ## Contact Info
......
# Ability Framework Overview # Ability Framework Overview
An ability is the abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances. Ability is the basic abstraction of applications in OpenHarmony.
Each ability is an application component that provides an independent service and is the minimum unit for the system to schedule an application. An application can contain one or more **Ability** instances.
The ability framework model has two forms: The ability framework model has two forms:
- FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there is Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities. - FA model, which is available for application development using API version 8 and earlier versions. In the FA model, there are PageAbility, ServiceAbility, DataAbility, and FormAbility.
- Stage model, which is introduced since API version 9. In the stage model, there is `PageAbility` and `ExtensionAbility`. `ExtensionAbility` is further extended to `ServiceExtensionAbility`, `FormExtensionAbility`, `DataShareExtensionAbility`, and more. - Stage model, which is introduced since API version 9. In the stage model, there are two classes: UIAbility and ExtensionAbility. ExtensionAbility is further extended to ServiceExtensionAbility, FormExtensionAbility, DataShareExtensionAbility, and more.
Starting from API version 9, the stage model is recommended.
The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models. The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models.
| Item | FA Model | Stage Model | | Item | FA Model | Stage Model |
| -------------- | ------------------------------------------------------------ | -------------------------------------------------------- | | -------------- | ------------------------------------------------------------ | -------------------------------------------------------- |
| Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. | | Application component development mode | Web-like development | Object-oriented development |
| Engine instance | Each ability in a process exclusively uses a JS VM engine instance. | Multiple abilities in a process share one JS VM engine instance. | | Engine instance | Each **Ability** instance exclusively occupies a VM instance. | Multiple **Ability** instances share a VM instance. |
| Intra-process object sharing| Not supported. | Supported. | | Intra-process object sharing| Not supported | Supported |
| Bundle description file | The `config.json` file is used to describe the HAP and component information. Each component must use a fixed file name.| The `module.json5` file is used to describe the HAP and component information. The entry file name can be specified.| | Bundle description file | The **config.json** file is used to describe the HAP and component information. Each component must use a fixed file name.| The **module.json5** file is used to describe the HAP and component information. The entry file name can be specified.|
| Component | Four types of components are provided: Page ability (used for UI page display), Service ability (used to provide services), Data ability (used for data sharing), and Form ability (used to provide widgets).| Two types of components are provided: Ability (used for UI page display) and Extension (scenario-based service extension). | | Component | Four types of components are provided: PageAbility (used for UI page display), ServiceAbility (used to provide services), DataAbility (used for data sharing), and FormAbility (used to provide widgets).| Two types of components are provided: UIAbility (used for UI page display) and ExtensionAbility (scenario-based service extension). |
In addition, the following differences exist in the development process: In addition, the following differences exist in the development process:
......
...@@ -96,13 +96,13 @@ Obtain the context by calling **context.getApplicationContext()** in **Ability** ...@@ -96,13 +96,13 @@ Obtain the context by calling **context.getApplicationContext()** in **Ability**
**Example** **Example**
```javascript ```javascript
import AbilityStage from "@ohos.application.AbilityStage"; import Ability from "@ohos.application.Ability";
var lifecycleid; var lifecycleid;
export default class MyAbilityStage extends AbilityStage { export default class MainAbility extends Ability {
onCreate() { onCreate() {
console.log("MyAbilityStage onCreate") console.log("MainAbility onCreate")
let AbilityLifecycleCallback = { let AbilityLifecycleCallback = {
onAbilityCreate(ability){ onAbilityCreate(ability){
console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability));
...@@ -141,7 +141,7 @@ export default class MyAbilityStage extends AbilityStage { ...@@ -141,7 +141,7 @@ export default class MyAbilityStage extends AbilityStage {
// 2. Use applicationContext to register and listen for the ability lifecycle in the application. // 2. Use applicationContext to register and listen for the ability lifecycle in the application.
lifecycleid = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); lifecycleid = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback);
console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid)); console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid));
} },
onDestroy() { onDestroy() {
let applicationContext = this.context.getApplicationContext(); let applicationContext = this.context.getApplicationContext();
applicationContext.unregisterAbilityLifecycleCallback(lifecycleid, (error, data) => { applicationContext.unregisterAbilityLifecycleCallback(lifecycleid, (error, data) => {
...@@ -211,7 +211,13 @@ export default class MainAbility extends Ability { ...@@ -211,7 +211,13 @@ export default class MainAbility extends Ability {
let context = this.context; let context = this.context;
console.log("[Demo] MainAbility bundleName " + context.abilityInfo.bundleName) console.log("[Demo] MainAbility bundleName " + context.abilityInfo.bundleName)
windowStage.setUIContent(this.context, "pages/index", null) windowStage.loadContent("pages/index", (err, data) => {
if (err.code) {
console.error('Failed to load the content. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data))
});
} }
onWindowStageDestroy() { onWindowStageDestroy() {
...@@ -237,7 +243,7 @@ For details, see [FormExtensionContext](../reference/apis/js-apis-formextensionc ...@@ -237,7 +243,7 @@ For details, see [FormExtensionContext](../reference/apis/js-apis-formextensionc
### Obtaining the Context on an ArkTS Page ### Obtaining the Context on an ArkTS Page
In the stage model, in the `onWindowStageCreate` lifecycle of an ability, you can call `SetUIContent` of `WindowStage` to load an ArkTS page. In some scenarios, you need to obtain the context on the page to call related APIs. In the stage model, in the onWindowStageCreate lifecycle of an ability, you can call **SetUIContent** of **WindowStage** to load an ArkTS page. In some scenarios, you need to obtain the context on the page to call related APIs.
**How to Obtain** **How to Obtain**
...@@ -245,7 +251,7 @@ Use the API described in the table below to obtain the context associated with a ...@@ -245,7 +251,7 @@ Use the API described in the table below to obtain the context associated with a
| API | Description | | API | Description |
| :------------------------------------ | :--------------------------- | | :------------------------------------ | :--------------------------- |
| getContext(component: Object): Object | Obtains the `Context` object associated with a component on the page.| | getContext(component: Object): Object | Obtains the **Context** object associated with a component on the page.|
**Example** **Example**
......
# FA Model Overview # FA Model Overview
## Overall Architecture ## Overall Architecture
The development of an OpenHarmony application is essentially the development of one or more abilities. By scheduling abilities and managing their lifecycle, OpenHarmony implements application scheduling.
The 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. Ability is the entry for application development in OpenHarmony.
- 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 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.
## Lifecycle The core of ability development is the processing on ability lifecycle callbacks.
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 Feature Ability (FA) model can be used only for application development using API version 8 and earlier versions. In this model, there are PageAbility, ServiceAbility, DataAbility, and FormAbility.
- PageAbility implements the ArkUI and provides the capability for interacting with users.
- ServiceAbility does not have a UI. It runs in the background and provides custom services for other abilities to invoke.
- DataAbility does not have a UI. It runs in the background and enables other abilities to insert, delete, and query data.
- FormAbility is used to implement widgets, a new UI display form available on OpenHarmony devices.
**The following figure shows the lifecycle of the Page ability.** > Note: Starting from API version 9, the stage model is recommended for application development.
![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png) ## Lifecycle
The other abilities do not involve the foreground/background switchover and the **onShow** callback. Among all abilities, PageAbility has the most complex lifecycle, because it has a UI and acts as a touchpoint for interacting with users.
You can override the lifecycle callbacks in **app.js/app.ets** to process application logic. **The following figure shows the lifecycle of PageAbility.**
Currently, the **app.js** file provides only the **onCreate** and **onDestroy** callbacks, and the **app.ets** file provides the full lifecycle callbacks. ![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png)
The other abilities do not involve foreground and background switch or the **onShow** and **onHide** callbacks.
You can override the lifecycle callbacks in **app.js** or **app.ets** to process application logic.
The **app.js** file provides only the **onCreate** and **onDestroy** callbacks, and the **app.ets** file provides the callbacks covering the entire lifecycle.
## Process and Thread Model ## Process and Thread Model
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.
Each application runs in a process. In the FA model, each ability runs in an independent VM.
When an ability is started, an application process as well as a thread for this ability is created. For an application that has multiple abilities, each ability runs in an independent thread. In the FA model, each ability is bound to an independent VM instance. In this way, abilities are isolated from each other.
![fa-threading-model](figures/fa-threading-model.png) ![fa-threading-model](figures/fa-threading-model.png)
......
...@@ -32,19 +32,19 @@ Example URIs: ...@@ -32,19 +32,19 @@ Example URIs:
**Table 1** Data ability lifecycle APIs **Table 1** Data ability lifecycle APIs
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|onInitialized?(info: AbilityInfo): void|Called during ability initialization to initialize the relational database (RDB).| |onInitialized(info: AbilityInfo): void|Called during ability initialization to initialize the relational database (RDB).|
|update?(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>): void|Updates data in the database.| |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.| |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.| |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.| |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.| |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.| |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.| |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.| |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.| |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.| |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.| |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.| |call(method: string, arg: string, extras: PacMap, callback: AsyncCallback\<PacMap>): void|Calls a custom API.|
## How to Develop ## How to Develop
...@@ -55,6 +55,7 @@ Example URIs: ...@@ -55,6 +55,7 @@ Example URIs:
The following code snippet shows how to create a Data ability: The following code snippet shows how to create a Data ability:
```javascript ```javascript
import featureAbility from '@ohos.ability.featureAbility'
import dataAbility from '@ohos.data.dataAbility' import dataAbility from '@ohos.data.dataAbility'
import dataRdb from '@ohos.data.rdb' import dataRdb from '@ohos.data.rdb'
...@@ -66,7 +67,8 @@ Example URIs: ...@@ -66,7 +67,8 @@ Example URIs:
export default { export default {
onInitialized(abilityInfo) { onInitialized(abilityInfo) {
console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName) console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName)
dataRdb.getRdbStore(STORE_CONFIG, 1, (err, store) => { let context = featureAbility.getContext()
dataRdb.getRdbStore(context, STORE_CONFIG, 1, (err, store) => {
console.info('DataAbility getRdbStore callback') console.info('DataAbility getRdbStore callback')
store.executeSql(SQL_CREATE_TABLE, []) store.executeSql(SQL_CREATE_TABLE, [])
rdbStore = store rdbStore = store
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
## Design Ideas ## Design Ideas
The stage model is designed to make it easier to develop complex applications in the distributed environment. The stage model is designed to provide a better application development mode in the distributed environment.
The following figure shows the design ideas of the stage model. The following figure shows the design ideas of the stage model.
...@@ -10,18 +10,17 @@ The following figure shows the design ideas of the stage model. ...@@ -10,18 +10,17 @@ The following figure shows the design ideas of the stage model.
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** - Efficient management of application processes
On a running device, resources are preferentially guaranteed for foreground applications, on the prerequisites that the overall power consumption requirements of the system are met. The stage model balances the application capabilities and overall system power consumption through ability and UI separation, strict background control, scenario-based service mechanism, and single-process model. As the device memory becomes larger, the number of processes concurrently running in the system increases. If the number of concurrent processes reaches several hundreds, the overall power consumption and performance of the system will be adversely affected without effective management measures. To restrict the behavior of background processes, the stage model uses four measures: transient task, continuous task, agent task, and Work Scheduler task. With these measures, foreground processes will obtain guaranteed resources, thereby delivering a better user experience.
- **Native support for component continuation and collaboration** - Native support for cross-device migration and multi-device collaboration
OpenHarmony natively supports distributed deployment. Therefore, its application framework must be designed for easier component migration and collaboration. The stage model achieves this design objective by providing features such as separation between ability and UI as well as integration of UI display and service capabilities. OpenHarmony is a native distributed OS. Its application framework must be designed for easier component migration and collaboration across devices. The stage model achieves this design objective by providing features such as separation between ability and UI as well as integration of UI display and service capabilities.
- **Support for multiple device types and window forms** - Different window forms for various device types
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.
The stage model redefines the ability lifecycle. In terms of architecture, the component manager and window manager are decoupled. This facilitates adaptation between window forms and device types.
## Basic Concepts ## Basic Concepts
...@@ -29,40 +28,42 @@ The following figure shows the basic concepts in the stage model. ...@@ -29,40 +28,42 @@ The following figure shows the basic concepts in the stage model.
![stageconcept](figures/stageconcept.png) ![stageconcept](figures/stageconcept.png)
- **HAP**: Harmony Ability Package, also called module, which is the basic unit for building, distributing, and loading OpenHarmony applications. Each HAP has a unique name, which is called **moduleName**, in an application. - **HAP**: basic unit for building, distributing, and loading OpenHarmony applications. Each HAP corresponds to a module in the development state. In an application, **moduleName** uniquely identifies a module.
- **Bundle**: an OpenHarmony application identified by **appid**. A bundle can contain multiple HAP files. Each application has a **bundleName**. However, **bundleName** must be used together with **appid** and other information to uniquely identify an application. - **Bundle**: an OpenHarmony application identified by **appid**. A bundle can contain multiple HAP files. Each application has a **bundleName**. However, **bundleName** must be used together with **appid** and other information to uniquely identify an application.
- **AbilityStage**: runtime class of an HAP. It is created when the HAP is loaded to the process for the first time and is visible to developers in the runtime. - **AbilityStage**: runtime object of an HAP. It is created when the HAP is loaded to the process for the first time and is visible to developers in the runtime.
- **Application**: runtime class of a bundle, which is invisible to developers in the runtime. - **Application**: runtime object of a bundle. It is invisible to developers in the runtime.
- **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. - **Context**: base class that provides APIs in the runtime to obtain information such as the bundle name, module name, and path. The **Context** classes of the Ability and ExtensionAbility components inherit from this class.
- **Ability**: class that provides lifecycle callbacks, holds the **AbilityContext** class, and supports component continuation and collaboration. - **Ability**: provides lifecycle callbacks, holds the ability context, and supports cross-device component migration and multi-device collaboration.
- **ExtensionAbility**: general name of scenario-based service extension abilities. The system defines multiple scenario-based **ExtensionAbility** classes, each of which has its own **ExtensionContext**. - **ExtensionAbility**: general name of scenario-based Extension abilities. The system defines multiple scenario-based **ExtensionAbility** classes, each of which has its own **ExtensionContext**.
- **WindowStage**: local window manager. - **WindowStage**: local window manager.
- **Window**: basic unit managed by the window manager. It has an ArkUI engine instance. - **Window**: application window, which holds an ArkUI engine instance.
- **ArkUI Page**: ArkUI development framework page. - **ArkUI Page**: UI developed based on ArkUI.
## Lifecycle ## Lifecycle
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. The ability and ability stage are key objects in the application lifecycle.
For details about the lifecycle differences between the stage model and FA model, see [Ability Framework Overview](ability-brief.md). This section focuses on the ability lifecycle transition and the scheduling relationships between the ability, ability stage, and window stage.
![stageabilitylifecyclecallback](figures/stageabilitylifecyclecallback.png) ![stageabilitylifecyclecallback](figures/stageabilitylifecyclecallback.png)
To implement 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. To implement device adaptation and multi-window scalability, OpenHarmony decouples the component manager from the window manager.
There are two lifecycle states related to **WindowStage** in **Ability**: **onWindowStageCreate** and **onWindowStageDestroy**. They are valid only for devices with the window display capability. **onWindowStageCreate** is invoked when a window stage is created, where you can call **loadContent** to set pages to be loaded for the ability. **onWindowStageDestroy** is invoked when the window stage is destroyed, where you can release resources. 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 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 state changes, so the component manager only senses the foreground and background state changes but not the focus changes.
There are two lifecycle states related to the window stage in **Ability**: **onWindowStageCreate** and **onWindowStageDestroy**. They are valid only for devices with the display capability. **onWindowStageCreate** is invoked when a window stage is created, where you can call **loadContent** to set pages to be loaded for the ability. **onWindowStageDestroy** is invoked when the window stage is destroyed, where you can release resources.
## Ability Instances and Missions ## Ability Instances and Missions
Abilities can be started in any of the following modes: Abilities can be started in any of the following modes:
+ **Singleton**: For each type of ability, only one instance exists in the application process. **Ability1** in the figure below is started in singleton mode. * **Singleton**: For each type of ability, only one instance exists in the application process. **Ability1** in the figure below is started in singleton mode.
* **Standard**: Each time **startAbility** is called, an instance of the specified ability type is created in the application process. **Ability2** in the figure below is started in standard mode.
+ **Standard**: Each time **startAbility** is called, an instance of the specified ability type is created in the application process. **Ability2** in the figure below is started in standard mode. * **Specified**: Before creating an **Ability** instance, you can create a key for the instance. Each time **startAbility** is called, the system asks the application which ability instance (corresponding to a key) will be used. **Ability3** in the figure below is started in specified mode.
+ **Specified**: Before creating an **Ability** instance, you can create a key for the instance. Each time **startAbility** is called, the system asks the application which ability instance (corresponding to a key) will be used. **Ability3** in the figure below is started in specified mode. Each **Ability** instance corresponds to a mission in **Recents**.
Each ability instance corresponds to a mission in **Launcher Recent**.
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. 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.
...@@ -70,33 +71,37 @@ The mission corresponding to an ability instance has a snapshot of the ability i ...@@ -70,33 +71,37 @@ The mission corresponding to an ability instance has a snapshot of the ability i
## ExtensionAbility Mechanism ## ExtensionAbility Mechanism
Different from the ability used for page display, the extension ability provides a restricted service running environment. It has the following features: Different from the ability used for UI display, ExtensionAbility provides a restricted running environment.
ExtensionAbility has the following features:
- Its process runs independently from the main process and shares the same storage sandbox with the main process. There is no inter-process communication (IPC) between the process and the main process. - Its process runs independently from the main process but shares the same storage sandbox with the main process. There is no inter-process communication (IPC) between the ExtensionAbility process and the main process.
- It has an independent context that provides scenario-specific APIs. - It has an independent context that provides scenario-specific APIs.
- It is created by the system, rather than by applications. - It is created by the system, rather than by applications.
- The lifecycles of the extension ability and process are managed by the system. - The lifecycles of the ExtensionAbility component and process are managed by the system.
The following figure uses the widget scenario as an example. You can inherit from the **FormExtensionAbility** base class to provide the widget details. The lifecycle of the **FormExtensionAbility** instance and that of the extension ability process where the instance is located are managed by **FormManagerService**, which is a system service. The following figure uses the widget an example. **FormExtensionAbility** is the base class. You can inherit from this class to provide widget information. The lifecycle of the **FormExtensionAbility** instance and that of the ExtensionAbility process where the instance is located are managed by a system service named **FormManagerService**.
![ExtensionAbility](figures/ExtensionAbility.png) ![ExtensionAbility](figures/ExtensionAbility.png)
## Process Model ## Process Model
All OpenHarmony applications are designed to meet the single-process model. In the single-process model, all processes in the application are created and managed by the system. Each application supports a maximum of three types of processes: OpenHarmony forces strong control policies on application processes. No APIs are provided to configure multiple processes. All application processes are created and managed by the system.
The processes of an application can be classified into three types:
- Main process: runs all ability components, pages, and service logic. - Main process: runs the **UIAbility** component, UI, and service logic.
- Extension process: runs classes derived from **ExtensionAbility** in the application. The lifecycle of this process is managed by a scenario-specific system service. - Extension process: runs classes derived from **ExtensionAbility** in the application. The lifecycle of this process is managed by a scenario-specific system service.
- Render process: created for the WebView and used to load the WebView rendering library. - Render process: created for the WebView and used to load the WebView rendering library.
The following figure shows the process model of an application. The following figure shows the process model of an application.
![stageprocessmodel](figures/stageprocessmodel.png) ![stageprocessmodel](figures/stageprocessmodel.png)
## Application Package Structure ## Application Package Structure
......
...@@ -2,9 +2,9 @@ ...@@ -2,9 +2,9 @@
## When to Use ## When to Use
Ability call is an extension of the ability capability. It enables an ability to be invoked by and communicate with external systems. The ability invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two abilities (caller ability and callee ability) through inter-process communication (IPC). Ability call is an extension of the ability capability. It enables an ability to be invoked by and communicate with external systems. The ability invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two abilities (caller ability and callee ability) through inter-process communication (IPC).
The core API used for the ability call is `startAbilityByCall`, which differs from `startAbility` in the following ways: The core API used for the ability call is **startAbilityByCall**, which differs from **startAbility** in the following ways:
- `startAbilityByCall` supports ability startup in the foreground and background, whereas `startAbility` supports ability startup in the foreground only. - **startAbilityByCall** supports ability startup in the foreground and background, whereas **startAbility** supports ability startup in the foreground only.
- The caller ability can use the `Caller` object returned by `startAbilityByCall` to communicate with the callee ability, but `startAbility` does not provide the communication capability. - The caller ability can use the **Caller** object returned by **startAbilityByCall** to communicate with the callee ability, but **startAbility** does not provide the communication capability.
Ability call is usually used in the following scenarios: Ability call is usually used in the following scenarios:
- Communicating with the callee ability - Communicating with the callee ability
...@@ -15,17 +15,17 @@ Ability call is usually used in the following scenarios: ...@@ -15,17 +15,17 @@ Ability call is usually used in the following scenarios:
|:------|:------| |:------|:------|
|Caller ability|Ability that triggers the ability call.| |Caller ability|Ability that triggers the ability call.|
|Callee ability|Ability invoked by the ability call.| |Callee ability|Ability invoked by the ability call.|
|Caller |Object returned by `startAbilityByCall` and used by the caller ability to communicate with the callee ability.| |Caller |Object returned by **startAbilityByCall** and used by the caller ability to communicate with the callee ability.|
|Callee |Object held by the callee ability to communicate with the caller ability.| |Callee |Object held by the callee ability to communicate with the caller ability.|
|IPC |Inter-process communication.| |IPC |Inter-process communication.|
The ability call process is as follows: The ability call process is as follows:
- The caller ability uses `startAbilityByCall` to obtain a `Caller` object and uses `call()` of the `Caller` object to send data to the callee ability. - The caller ability uses **startAbilityByCall** to obtain a **Caller** object and uses **call()** of the **Caller** object to send data to the callee ability.
- The callee ability, which holds a `Callee` object, uses `on()` of the `Callee` object to register a callback. This callback is invoked when the callee ability receives data from the caller ability. - The callee ability, which holds a **Callee** object, uses **on()** of the **Callee** object to register a callback. This callback is invoked when the callee ability receives data from the caller ability.
![stage-call](figures/stage-call.png) ![stage-call](figures/stage-call.png)
> **NOTE**<br/> > **NOTE**<br/>
> The launch type of the callee ability must be `singleton`. > The launch type of the callee ability must be **singleton**.
> Currently, only system applications can use the ability call. > Currently, only system applications can use the ability call.
## Available APIs ## Available APIs
...@@ -34,30 +34,29 @@ The table below describes the ability call APIs. For details, see [Ability](../r ...@@ -34,30 +34,29 @@ The table below describes the ability call APIs. For details, see [Ability](../r
**Table 2** Ability call APIs **Table 2** Ability call APIs
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|startAbilityByCall(want: Want): Promise\<Caller>|Starts an ability in the foreground (through the `want` configuration) or background (default) and obtains the `Caller` object for communication with the ability. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-service-extension-context.md#serviceextensioncontextstartabilitybycall).| |startAbilityByCall(want: Want): Promise\<Caller>|Starts an ability in the foreground (through the **want** configuration) or background (default) and obtains the **Caller** object for communication with the ability. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-service-extension-context.md#serviceextensioncontextstartabilitybycall).|
|on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee ability registers a method.| |on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee ability registers a method.|
|off(method: string): void|Callback invoked when the callee ability deregisters a method.| |off(method: string): void|Callback invoked when the callee ability deregisters a method.|
|call(method: string, data: rpc.Sequenceable): Promise\<void>|Sends agreed sequenceable data to the callee ability.| |call(method: string, data: rpc.Sequenceable): Promise\<void>|Sends agreed sequenceable data to the callee ability.|
|callWithResult(method: string, data: rpc.Sequenceable): Promise\<rpc.MessageParcel>|Sends agreed sequenceable data to the callee ability and obtains the agreed sequenceable data returned by the callee ability.| |callWithResult(method: string, data: rpc.Sequenceable): Promise\<rpc.MessageParcel>|Sends agreed sequenceable data to the callee ability and obtains the agreed sequenceable data returned by the callee ability.|
|release(): void|Releases the `Caller` object.| |release(): void|Releases the **Caller** object.|
|onRelease(callback: OnReleaseCallBack): void|Callback invoked when the `Caller` object is released.| |on(type: "release", callback: OnReleaseCallback): void|Callback invoked when the **Caller** object is released.|
## How to Develop ## How to Develop
The procedure for developing the ability call is as follows: The procedure for developing the ability call is as follows:
1. Create a callee ability. 1. Create a callee ability.
2. Access the callee ability. 2. Access the callee ability.
> **NOTE**
>
> The code snippets provided in the **How to Develop** section are used to show specific development steps. They may not be able to run independently.
### Creating a Callee Ability ### Creating a Callee Ability
For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use `on()` to register a listener. When data does not need to be received, use `off()` to deregister the listener. For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener.
**1. Configure the ability launch type.** **1. Configure the ability launch type.**
Set `launchType` of the callee ability to `singleton` in the `module.json5` file. Set **launchType** of the callee ability to **singleton** in the **module.json5** file.
|JSON Field|Description| |JSON Field|Description|
|:------|:------| |:------|:------|
|"launchType"|Ability launch type. Set this parameter to `singleton`.| |"launchType"|Ability launch type. Set this parameter to **singleton**.|
An example of the ability configuration is as follows: An example of the ability configuration is as follows:
```json ```json
...@@ -73,7 +72,7 @@ An example of the ability configuration is as follows: ...@@ -73,7 +72,7 @@ An example of the ability configuration is as follows:
``` ```
**2. Import the Ability module.** **2. Import the Ability module.**
```ts ```ts
import Ability from '@ohos.application.Ability' import Ability from '@ohos.app.ability.UIAbility'
``` ```
**3. Define the agreed sequenceable data.** **3. Define the agreed sequenceable data.**
...@@ -101,9 +100,9 @@ export default class MySequenceable { ...@@ -101,9 +100,9 @@ export default class MySequenceable {
} }
} }
``` ```
**4. Implement `Callee.on` and `Callee.off`.** **4. Implement Callee.on and Callee.off.**
The time to register a listener for the callee ability 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 code snippet is as follows: The time to register a listener for the callee ability 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 code snippet is as follows:
```ts ```ts
const TAG: string = '[CalleeAbility]' const TAG: string = '[CalleeAbility]'
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg'
...@@ -143,16 +142,16 @@ export default class CalleeAbility extends Ability { ...@@ -143,16 +142,16 @@ export default class CalleeAbility extends Ability {
### Accessing the Callee Ability ### Accessing the Callee Ability
**1. Import the Ability module.** **1. Import the Ability module.**
```ts ```ts
import Ability from '@ohos.application.Ability' import Ability from '@ohos.app.ability.UIAbility'
``` ```
**2. Obtain the `Caller` object.** **2. Obtain the Caller object.**
The `context` attribute of the ability implements `startAbilityByCall` to obtain the `Caller` object for communication. The following example uses `this.context` to obtain the `context` attribute of the ability, uses `startAbilityByCall` to start the callee ability, obtain the `Caller` object, and register the `onRelease` listener of the caller ability. You need to implement processing based on service requirements. The code snippet is as follows: The **context** attribute of the ability implements **startAbilityByCall** to obtain the **Caller** object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the **Caller** object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. The code snippet is as follows:
```ts ```ts
// Register the onRelease listener of the caller ability. // Register the onRelease listener of the caller ability.
private regOnRelease(caller) { private regOnRelease(caller) {
try { try {
caller.onRelease((msg) => { caller.on("release", (msg) => {
console.log(`caller onRelease is called ${msg}`) console.log(`caller onRelease is called ${msg}`)
}) })
console.log('caller register OnRelease succeed') console.log('caller register OnRelease succeed')
...@@ -193,7 +192,7 @@ async onButtonGetRemoteCaller() { ...@@ -193,7 +192,7 @@ async onButtonGetRemoteCaller() {
caller = data caller = data
console.log('get remote caller success') console.log('get remote caller success')
// Register the onRelease listener of the caller ability. // Register the onRelease listener of the caller ability.
caller.onRelease((msg) => { caller.on("release", (msg) => {
console.log(`remote caller onRelease is called ${msg}`) console.log(`remote caller onRelease is called ${msg}`)
}) })
console.log('remote caller register OnRelease succeed') console.log('remote caller register OnRelease succeed')
...@@ -203,7 +202,7 @@ async onButtonGetRemoteCaller() { ...@@ -203,7 +202,7 @@ async onButtonGetRemoteCaller() {
}) })
} }
``` ```
Obtain the ID of the peer device from `DeviceManager`. Note that the `getTrustedDeviceListSync` API is open only to system applications. The 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 code snippet is as follows:
```ts ```ts
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedHardware.deviceManager';
var dmClass; var dmClass;
...@@ -248,7 +247,7 @@ async onButtonCall() { ...@@ -248,7 +247,7 @@ async onButtonCall() {
} }
``` ```
In the following, `CallWithResult` is used to send data `originMsg` to the callee ability and assign the data processed by the `CallSendMsg` method to `backMsg`. The code snippet is as follows: In the following, **CallWithResult** is used to send data **originMsg** to the callee ability and assign the data processed by the **CallSendMsg** method to **backMsg**. The code snippet is as follows:
```ts ```ts
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg'
originMsg: string = '' originMsg: string = ''
...@@ -268,9 +267,9 @@ async onButtonCallWithResult(originMsg, backMsg) { ...@@ -268,9 +267,9 @@ async onButtonCallWithResult(originMsg, backMsg) {
} }
} }
``` ```
**4. Release the `Caller` object.** **4. Release the Caller object.**
When the `Caller` object is no longer required, use `release()` to release it. The code snippet is as follows: When the **Caller** object is no longer required, use **release()** to release it. The code snippet is as follows:
```ts ```ts
releaseCall() { releaseCall() {
try { try {
......
...@@ -6,15 +6,15 @@ The Distributed Data Service (DDS) implements synchronization of application dat ...@@ -6,15 +6,15 @@ The Distributed Data Service (DDS) implements synchronization of application dat
## Available APIs ## Available APIs
For details about the APIs, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md).
For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis-distributedKVStore.md).
**Table 1** APIs provided by the DDS **Table 1** APIs provided by the DDS
| API | Description | | API | Description |
| ------------------------------------------------------------ | ----------------------------------------------- | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KVManager** object for database management.| | createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KvManager** object for database management. |
| getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Obtains a KV store with the specified **Options** and **storeId**.| | getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Creates and obtains a KV store.|
| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array\|string\|number\|boolean): Promise&lt;void> | Inserts and updates data. | | put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array\|string\|number\|boolean): Promise&lt;void> | Inserts and updates data. |
| delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. | | delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. |
| get(key: string, callback: AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;): void<br>get(key: string): Promise&lt;Uint8Array\|string\|boolean\|number> | Queries data. | | get(key: string, callback: AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;): void<br>get(key: string): Promise&lt;Uint8Array\|string\|boolean\|number> | Queries data. |
...@@ -28,8 +28,9 @@ The following uses a single KV store as an example to describe the development p ...@@ -28,8 +28,9 @@ The following uses a single KV store as an example to describe the development p
1. Import the distributed data module. 1. Import the distributed data module.
```js ```js
import distributedData from '@ohos.data.distributedData'; import distributedKVStore from '@ohos.data.distributedKVStore';
``` ```
2. Apply for the required permission if data synchronization is required. 2. Apply for the required permission if data synchronization is required.
Add the permission required (FA model) in the **config.json** file. The sample code is as follows: Add the permission required (FA model) in the **config.json** file. The sample code is as follows:
...@@ -45,6 +46,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -45,6 +46,7 @@ The following uses a single KV store as an example to describe the development p
} }
} }
``` ```
For the apps based on the stage model, see [Declaring Permissions](../security/accesstoken-guidelines.md#stage-model). For the apps based on the stage model, see [Declaring Permissions](../security/accesstoken-guidelines.md#stage-model).
This permission must also be granted by the user when the application is started for the first time. The sample code is as follows: This permission must also be granted by the user when the application is started for the first time. The sample code is as follows:
...@@ -88,10 +90,10 @@ The following uses a single KV store as an example to describe the development p ...@@ -88,10 +90,10 @@ The following uses a single KV store as an example to describe the development p
grantPermission(); grantPermission();
``` ```
3. Create a **kvManager** instance based on the specified **kvManagerConfig** object. 3. Create a **KvManager** instance based on the specified **KvManagerConfig** object.
1. Create a **kvManagerConfig** object based on the application context. 1. Create a **kvManagerConfig** object based on the application context.
2. Create a **kvManager** instance. 2. Create a **KvManager** instance.
The sample code is as follows: The sample code is as follows:
...@@ -113,22 +115,18 @@ The following uses a single KV store as an example to describe the development p ...@@ -113,22 +115,18 @@ The following uses a single KV store as an example to describe the development p
try { try {
const kvManagerConfig = { const kvManagerConfig = {
bundleName: 'com.example.datamanagertest', bundleName: 'com.example.datamanagertest',
userInfo: {
context:context, context:context,
userId: '0',
userType: distributedData.UserType.SAME_USER_ID
}
} }
distributedData.createKVManager(kvManagerConfig, function (err, manager) { distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) {
if (err) { if (err) {
console.log('Failed to create KVManager: ${error}'); console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Created KVManager successfully'); console.log('Created KVManager successfully');
kvManager = manager; kvManager = manager;
}); });
} catch (e) { } catch (e) {
console.log('An unexpected error occurred. Error: ${e}'); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -147,19 +145,19 @@ The following uses a single KV store as an example to describe the development p ...@@ -147,19 +145,19 @@ The following uses a single KV store as an example to describe the development p
encrypt: false, encrypt: false,
backup: false, backup: false,
autoSync: false, autoSync: false,
kvStoreType: distributedData.KVStoreType.SINGLE_VERSION, kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
securityLevel: distributedData.SecurityLevel.S0 securityLevel: distributedKVStore.SecurityLevel.S1
}; };
kvManager.getKVStore('storeId', options, function (err, store) { kvManager.getKVStore('storeId', options, function (err, store) {
if (err) { if (err) {
console.log('Failed to get KVStore: ${err}'); console.error(`Failed to get KVStore: code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Got KVStore successfully'); console.log('Obtained KVStore successfully');
kvStore = store; kvStore = store;
}); });
} catch (e) { } catch (e) {
console.log('An unexpected error occurred. Error: ${e}'); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -172,9 +170,13 @@ The following uses a single KV store as an example to describe the development p ...@@ -172,9 +170,13 @@ The following uses a single KV store as an example to describe the development p
The following is the sample code for subscribing to the data changes of a single KV store: The following is the sample code for subscribing to the data changes of a single KV store:
```js ```js
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { try{
console.log("dataChange callback call data: ${data}"); kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
console.log(`dataChange callback call data: ${data}`);
}); });
}catch(e){
console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`);
}
``` ```
6. Write data to the single KV store. 6. Write data to the single KV store.
...@@ -188,15 +190,15 @@ The following uses a single KV store as an example to describe the development p ...@@ -188,15 +190,15 @@ The following uses a single KV store as an example to describe the development p
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
if (err != undefined) { if (err != undefined) {
console.log('Failed to put data: ${error}'); console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Put data successfully'); console.log('Put data successfully');
}); });
} catch (e) { }catch (e) {
console.log('An unexpected error occurred. Error: ${e}'); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -211,18 +213,22 @@ The following uses a single KV store as an example to describe the development p ...@@ -211,18 +213,22 @@ The following uses a single KV store as an example to describe the development p
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
if (err != undefined) { if (err != undefined) {
console.log('Failed to put data: ${error}'); console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Put data successfully'); console.log('Put data successfully');
kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) {
console.log('Got data successfully: ${data}'); if (err != undefined) {
console.error(`Failed to get data.code is ${err.code},message is ${err.message}`);
return;
}
console.log(`Obtained data successfully:${data}`);
}); });
}); });
} catch (e) { }catch (e) {
console.log('An unexpected error occurred. Error: ${e}'); console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -254,9 +260,9 @@ The following uses a single KV store as an example to describe the development p ...@@ -254,9 +260,9 @@ The following uses a single KV store as an example to describe the development p
} }
try{ try{
// 1000 indicates that the maximum delay is 1000 ms. // 1000 indicates that the maximum delay is 1000 ms.
kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000); kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000);
} catch (e) { } catch (e) {
console.log('An unexpected error occurred. Error: ${e}'); console.error(`An unexpected error occurred. code is ${e.code},message is ${e.message}`);
} }
} }
}); });
......
...@@ -28,26 +28,29 @@ Obtain a **Preferences** instance for data operations. A **Preferences** instanc ...@@ -28,26 +28,29 @@ Obtain a **Preferences** instance for data operations. A **Preferences** instanc
| --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ohos.data.preferences | getPreferences(context: Context, name: string): Promise\<Preferences> | Obtains a **Preferences** instance.| | ohos.data.preferences | getPreferences(context: Context, name: string): Promise\<Preferences> | Obtains a **Preferences** instance.|
### Accessing Data ### Processing Data
Call the **put()** method to add or modify data in a **Preferences** instance. Call **put()** to add or modify data in a **Preferences** instance.
Call the **get()** method to read data from a **Preferences** instance. Call **get()** to read data from a **Preferences** instance.
Call **getAll()** to obtain an **Object** instance that contains all KV pairs in a **Preferences** instance. Call **getAll()** to obtain an **Object** instance that contains all KV pairs in a **Preferences** instance.
**Table 2** APIs for accessing **Preferences** data Call **delete()** to delete the KV pair of the specified key from the **Preferences** instance.
**Table 2** APIs for processing **Preferences** data
| Class | API | Description | | Class | API | Description |
| ----------- | ---------------------------------------------------------- | ------------------------------------------------------------ | | ----------- | ---------------------------------------------------------- | ------------------------------------------------------------ |
| Preferences | put(key: string, value: ValueType): Promise\<void> | Writes data to the **Preferences** instance. The value to write can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| | Preferences | put(key: string, value: ValueType): Promise\<void> | Writes data to the **Preferences** instance. The value to write can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.|
| Preferences | get(key: string, defValue: ValueType): Promise\<ValueType> | Obtains data from the **Preferences** instance. The value to read can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| | Preferences | get(key: string, defValue: ValueType): Promise\<ValueType> | Obtains data from the **Preferences** instance. The value to read can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.|
| Preferences | getAll(): Promise<Object> | Obtains an **Object** instance that contains all KV pairs in the **Preferences** instance. | | Preferences | getAll(): Promise\<Object> | Obtains an **Object** instance that contains all KV pairs in the **Preferences** instance. |
| Preferences | delete(key: string): Promise\<void> | Deletes the KV pair of the specified key from the **Preferences** instance. |
### Storing Data Persistently ### Storing Data Persistently
Call the **flush()** method to write the cached data back to its text file for persistent storage. Call **flush()** to write the cached data back to its text file for persistent storage.
**Table 4** API for data persistence **Table 4** API for data persistence
...@@ -68,7 +71,7 @@ You can subscribe to data changes. When the value of the subscribed key is chang ...@@ -68,7 +71,7 @@ You can subscribe to data changes. When the value of the subscribed key is chang
### Deleting Data ### Deleting Data
Use the following APIs to delete a **Preferences** instance or data file. You can use the following APIs to delete a **Preferences** instance or data file.
**Table 6** APIs for deleting **Preferences** **Table 6** APIs for deleting **Preferences**
...@@ -130,7 +133,7 @@ Use the following APIs to delete a **Preferences** instance or data file. ...@@ -130,7 +133,7 @@ Use the following APIs to delete a **Preferences** instance or data file.
3. Write data. 3. Write data.
Use the **preferences.put()** method to write data to the **Preferences** instance. Use **preferences.put()** to write data to the **Preferences** instance.
```js ```js
let putPromise = preferences.put('startup', 'auto'); let putPromise = preferences.put('startup', 'auto');
...@@ -143,7 +146,7 @@ Use the following APIs to delete a **Preferences** instance or data file. ...@@ -143,7 +146,7 @@ Use the following APIs to delete a **Preferences** instance or data file.
4. Read data. 4. Read data.
Use the **preferences.get()** method to read data. Use **preferences.get()** to read data.
```js ```js
let getPromise = preferences.get('startup', 'default'); let getPromise = preferences.get('startup', 'default');
...@@ -156,7 +159,7 @@ Use the following APIs to delete a **Preferences** instance or data file. ...@@ -156,7 +159,7 @@ Use the following APIs to delete a **Preferences** instance or data file.
5. Store data persistently. 5. Store data persistently.
Use the **flush()** method to flush data from the **Preferences** instance to its file. Use **flush()** to flush data from the **Preferences** instance to its file.
```js ```js
preferences.flush(); preferences.flush();
...@@ -190,7 +193,7 @@ Use the following APIs to delete a **Preferences** instance or data file. ...@@ -190,7 +193,7 @@ Use the following APIs to delete a **Preferences** instance or data file.
7. Delete the specified file. 7. Delete the specified file.
Use the **deletePreferences** method to delete the **Preferences** instance and its persistent file and backup and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will be caused. The deleted data and files cannot be restored. Use **deletePreferences()** to delete the **Preferences** instance and its persistent file and backup and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will be caused. The deleted data and files cannot be restored.
```js ```js
let proDelete = data_preferences.deletePreferences(context, 'mystore'); let proDelete = data_preferences.deletePreferences(context, 'mystore');
......
# Device Usage Statistics # Device Usage Statistics
- [Device Usage Statistics Overview](device-usage-statistics-overview.md) - [Device Usage Statistics Overview](device-usage-statistics-overview.md)
- [Device Usage Statistics Development](device-usage-statistics-dev-guide.md) - [Device Usage Statistics Development](device-usage-statistics-use-guide.md)
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
## When to Use ## When to Use
In Host mode, you can obtain the list of connected devices, enable or disable the devices, manage device access permissions, and perform data transfer or control transfer. In Host mode, you can obtain the list of connected USB devices, enable or disable the devices, manage device access permissions, and perform data transfer or control transfer.
## APIs ## APIs
...@@ -16,6 +16,7 @@ The following table lists the USB APIs currently available. For details, see the ...@@ -16,6 +16,7 @@ The following table lists the USB APIs currently available. For details, see the
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| 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. | | 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. | | requestRight(deviceName: string): Promise\<boolean> | Requests the temporary permission for a given application to access the USB device. |
| removeRight(deviceName: string): boolean | Removes the 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()`. | | 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. | | getDevices(): Array<Readonly\<USBDevice>> | Obtains the USB device list. |
| setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. | | setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. |
......
...@@ -8,7 +8,7 @@ The event logging function helps applications log various information generated ...@@ -8,7 +8,7 @@ The event logging function helps applications log various information generated
JS application event logging APIs are provided by the **hiAppEvent** module. JS application event logging APIs are provided by the **hiAppEvent** module.
The following table provides only a brief description of related APIs. For details, see [HiAppEvent](../reference/apis/js-apis-hiappevent.md). The following table provides only a brief description of related APIs. For details, see [HiAppEvent](../reference/apis/js-apis-hiviewdfx-hiappevent.md).
**Table 1** APIs for application event logging **Table 1** APIs for application event logging
...@@ -17,17 +17,11 @@ The following table provides only a brief description of related APIs. For detai ...@@ -17,17 +17,11 @@ The following table provides only a brief description of related APIs. For detai
| write(AppEventInfo info, AsyncCallback\<void> callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result.| | write(AppEventInfo info, AsyncCallback\<void> callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result.|
| write(AppEventInfo info): Promise\<void> | Logs application events in asynchronous mode. This API uses a promise to return the result. | | write(AppEventInfo info): Promise\<void> | Logs application events in asynchronous mode. This API uses a promise to return the result. |
When an asynchronous callback is used, the return value can be processed directly in the callback.
If 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).
**Table 2** APIs for event logging configuration **Table 2** APIs for event logging configuration
| API | Description | | API | Description |
| --------------------------------------- | ---------------------------------------------------- | | ------------------------------------ | ---------------------------------------------------- |
| configure(ConfigOption config): boolean | Sets the configuration options for application event logging.| | configure(ConfigOption config): void | Sets the configuration options for application event logging.|
**Table 3** APIs for watcher management **Table 3** APIs for watcher management
...@@ -42,32 +36,14 @@ For details about the result codes, see [Event Verification Result Codes](#event ...@@ -42,32 +36,14 @@ For details about the result codes, see [Event Verification Result Codes](#event
| ----------------- | -------------------- | | ----------------- | -------------------- |
| clearData(): void | Clears local logging data.| | clearData(): void | Clears local logging data.|
### Event Verification Result Codes ## How to Develop
| Result Code| Cause | Verification Rules | Handling Method |
| ------ | ----------------------------- | ------------------------------------------------------------ | ---------------------------------------------------------- |
| 0 | N/A | Event verification is successful. | Event logging is normal. No action is required. |
| -1 | Invalid event name | The name is not empty and contains a maximum of 48 characters.<br>The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).<br>The 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 event parameter must be an object.| Ignore this event and do not perform logging. |
| -4 | Invalid event domain name | The name is not empty and contains a maximum of 32 characters.<br>The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).<br>The name does not start with a digit or underscore \(_).| Ignore this event and do not perform logging. |
| -99 | Application event logging disabled | Application event logging 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 name is not empty and contains a maximum of 16 characters.<br>The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).<br>The name does not start with a digit or underscore \(_).<br>The 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 | Invalid length for values of the string type| For a value of the string type, the maximum length is 8*1024 characters. | Truncate the value with the first 8*1024 characters retained, 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 | Invalid number of elements in values of the array type | For a value of the array type, the number of elements must be less than or equal to 100. | Truncate the array with the first 100 elements retained, and continue to perform logging. |
| 7 | Invalid parameters in values of the array type | For a value of the array type, all the parameters must be of the same type, which can only be boolean, number, or string.| Ignore the key-value pair and continue to perform logging. |
## Development Procedure
The following uses a one-time event watcher as an example to illustrate the development procedure. The following uses a one-time event watcher as an example to illustrate the development procedure.
1. Create an eTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index.ets**, and double-click **index.ets**. Then, add three buttons to simulate the process of watching for application events. Wherein, button 1 is used to invoke application event logging, button 2 to add an event watcher that automatically triggers a callback, and button 3 to remove the watcher. The complete sample code is as follows: 1. Create an eTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index.ets**, and double-click **index.ets**. Then, add three buttons to simulate the process of watching for application events. Wherein, button 1 is used to invoke application event logging, button 2 to add an event watcher that automatically triggers a callback, and button 3 to remove the watcher. The complete sample code is as follows:
```ts ```ts
import hiAppEvent from '@ohos.hiAppEvent'; import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent';
@Entry @Entry
@Component @Component
...@@ -91,10 +67,10 @@ The following uses a one-time event watcher as an example to illustrate the deve ...@@ -91,10 +67,10 @@ The following uses a one-time event watcher as an example to illustrate the deve
int_data: 100, int_data: 100,
str_data: "strValue" str_data: "strValue"
} }
}).then((value) => { }).then(() => {
console.log(`HiAppEvent success to write event: ${value}`); console.log(`HiAppEvent success to write event`);
}).catch((err) => { }).catch((err) => {
console.error(`HiAppEvent failed to write event because ${err.code}`); console.error(`code: ${err.code}, message: ${err.message}`);
}); });
}) })
...@@ -120,12 +96,12 @@ The following uses a one-time event watcher as an example to illustrate the deve ...@@ -120,12 +96,12 @@ The following uses a one-time event watcher as an example to illustrate the deve
// Obtain the event package based on the configured size threshold. If returned event package is null, all event data has been obtained. // Obtain the event package based on the configured size threshold. If returned event package is null, all event data has been obtained.
while ((eventPkg = holder.takeNext()) != null) { while ((eventPkg = holder.takeNext()) != null) {
// Parse the obtained event package and display the result on the Log page. // Parse the obtained event package and display the result on the Log page.
console.info('HiAppEvent eventPkg.packageId=' + eventPkg.packageId); console.info(`HiAppEvent eventPkg.packageId=${eventPkg.packageId}`);
console.info('HiAppEvent eventPkg.row=' + eventPkg.row); console.info(`HiAppEvent eventPkg.row=${eventPkg.row}`);
console.info('HiAppEvent eventPkg.size=' + eventPkg.size); console.info(`HiAppEvent eventPkg.size=${eventPkg.size}`);
// Traverse and parse event string arrays in the obtained event package. // Traverse and parse event string arrays in the obtained event package.
for (const eventInfo of eventPkg.data) { for (const eventInfo of eventPkg.data) {
console.info('HiAppEvent eventPkg.data=' + eventInfo); console.info(`HiAppEvent eventPkg.data=${eventInfo}`);
} }
} }
} }
...@@ -169,4 +145,4 @@ The following uses a one-time event watcher as an example to illustrate the deve ...@@ -169,4 +145,4 @@ The following uses a one-time event watcher as an example to illustrate the deve
The following sample is provided to help you better understand how to develop the application event logging feature: The following sample is provided to help you better understand how to develop the application event logging feature:
- [`JsDotTest` (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/DFX/JsDotTest) - [`JsDotTest`: Event Logging (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/DFX/JsDotTest)
# Overview of Application Event Logging # Overview of Application Event Logging
HiAppEvent provides event logging APIs for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of your application. The HiAppEvent module provides event logging APIs for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of your application.
The HiAppEvent module can be used to develop application event-related functions, including flushing application events to a disk and querying historical application events. You can use this module to develop application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration.
## Basic Concepts ## Basic Concepts
......
# FAQs # FAQs
- [Ability Framework Development](faqs-ability.md) - [Ability Framework Development](faqs-ability.md)
- [ArkUI (JavaScript) Development](faqs-ui-js.md) - [Bundle Management Development](faqs-bundle.md)
- [ArkUI (eTS) Development](faqs-ui-ets.md) - [ArkUI (eTS) Development](faqs-ui-ets.md)
- [ArkUI (JavaScript) Development](faqs-ui-js.md)
- [Graphics and Image Development](faqs-graphics.md) - [Graphics and Image Development](faqs-graphics.md)
- [File Management Development](faqs-file-management.md) - [File Management Development](faqs-file-management.md)
- [Media Development](faqs-media.md)
- [Network and Connection Development](faqs-connectivity.md) - [Network and Connection Development](faqs-connectivity.md)
- [Data Management Development](faqs-data-management.md) - [Data Management Development](faqs-data-management.md)
- [Device Management Development](faqs-device-management.md) - [Device Management Development](faqs-device-management.md)
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
A guide is available for the **DataShareExtensionAbility** class in the stage model, which provides APIs for sharing data with other applications and managing the data. A guide is available for the **DataShareExtensionAbility** class, which provides APIs for sharing data with other applications and managing the data, in the stage model.
Reference: [DataShare Development](../database/database-datashare-guidelines.md) Reference: [DataShare Development](../database/database-datashare-guidelines.md)
...@@ -20,6 +20,32 @@ Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 ...@@ -20,6 +20,32 @@ Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
Reference: [Release Testing Version](https://gitee.com/openharmony-sig/oh-inner-release-management/blob/master/Release-Testing-Version.md) Reference: [Release Testing Version](https://gitee.com/openharmony-sig/oh-inner-release-management/blob/master/Release-Testing-Version.md)
## How do I set the UI of an ability to transparent?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Set the background color of the top container component to transparent, and then set the **opacity** attribute of the XComponent to **0.01**.
Example:
```
build() {
Stack() {
XComponent({
id: 'componentId',
type: 'surface',
})
.width('100%')
.height('100%')
.opacity(0.01)
// Page content
}
.width('100%')
.height('100%')
.backgroundColor('rgba(255,255,255, 0)')
}
```
## How do I prevent "this" in a method from changing to "undefined" when the method is called? ## How do I prevent "this" in a method from changing to "undefined" when the method is called?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
...@@ -36,7 +62,7 @@ Configure the **startWindowIcon** attribute under **abilities** in the **module. ...@@ -36,7 +62,7 @@ Configure the **startWindowIcon** attribute under **abilities** in the **module.
Reference: [Application Package Structure Configuration File](../quick-start/stage-structure.md) Reference: [Application Package Structure Configuration File](../quick-start/stage-structure.md)
Example: Example:
``` ```
{ {
...@@ -58,3 +84,133 @@ Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 ...@@ -58,3 +84,133 @@ Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Implement the **onConfigurationUpdated** callback in the **Ability** class. The callback is triggered when the system language, color mode, or display parameters (such as the orientation and density) change. Implement the **onConfigurationUpdated** callback in the **Ability** class. The callback is triggered when the system language, color mode, or display parameters (such as the orientation and density) change.
Reference: [Ability Development](../ability/stage-ability.md) Reference: [Ability Development](../ability/stage-ability.md)
## Can I obtain the context through globalThis in the stage model?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Do not use **globalThis** to obtain the context in the stage model. This is because all the processes of an application share a JS VM instance in the stage model. Multiple abilities can run on these processes and share the same global object. If **globalThis** is used, the context of different abilities of the same JS VM instance may be returned.
For details about the recommended operation, see [Context in the Stage Model](../ability/context-userguide.md#context-in-the-stage-model).
## How do I obtain the HAP file installation path of application B from application A?
Applicable to: OpenHarmony SDK 3.0 or later, stage model of API version 9
First, request the system permission. For details, see [Having Your App Automatically Signed](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-auto-configuring-signature-information-0000001271659465). Then, import the **bundle** module, and call **bundle.getApplicationInfo()** to obtain application information based on the bundle name. Finally, use **application.moduleSourceDirs** to obtain the application storage path.
## How is data returned when startAbilityForResult is called?
Applicable to: OpenHarmony SDK3.0, stage model of API version 9
The callee uses **AbilityContext.terminateSelfWithResult** to destroy its ability and pass parameters to **startAbilityForResult**. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md#abilitycontextterminateselfwithresult).
## Can the lifecycle callback of a released FA widget be triggered when the widget is displayed in the service center so that the user login information can be obtained without opening the FA application?
Applicable to: OpenHarmony SDK 3.2.5.5, FA model of API version 8
After a widget is added, the **onCreate()** lifecycle is triggered so that related user information (silent login) can be displayed even when the application is not started. However, users must manually add the widget after the application is installed.
## How do I obtain the context?
Applicable to: OpenHarmony SDK 3.2.7.5, stage model of API version 9
You can use **this.context** to obtain the context in the **MainAbility.ts** file or call **getContext(this)** to obtain the context on the component page.
## What should I do when undefined is displayed for the calling of **abilityAccessCtrl.grantUserGrantedPermission** during API version 8 syntax verification?
Applicable to: OpenHarmony SDK 3.0, FA model of API version 8
**abilityAccessCtrl.grantUserGrantedPermission** is a system API. It is not available in the public SDK, which is provided as default on DevEco Studio. To use system APIs, switch to the full SDK. For details, see [Guide to Switching to Full SDK](../quick-start/full-sdk-switch-guide.md).
## Which of the following Extension abilities are available in the public SDK: ServiceExtensionAbility, FormExtensionAbility, and DataShareExtensionAbility?
Applicable to: OpenHarmony SDK 3.2.5.6, stage model of API version 9
Among the aforementioned Extension abilities, only **FormExtensionAbility** is available in the public SDK. **ServiceExtensionAbility** and **DataShareExtensionAbility** are system APIs and available only in the full SDK.
Public SDK: intended for application developers and does not contain system APIs that require system permissions.
Full SDK: intended for original equipment manufacturers (OEMs) and contains system APIs that require system permissions.
## Why can't I play GIF images cyclically on the widget?
Applicable to: OpenHarmony SDK 3.2.5.6, stage model of API version 9
The system does not support the display of GIF images on the widget.
## How do I implement service login by touching a widget?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
You can start an ability upon the touch and implement service login in the ability.
## How do I redirect to the application details page in Settings?
Applicable to: OpenHarmony SDK 3.2.6.5
Refer to the following code:
```
this.context.startAbility(
{
action: "action.settings.app.info",
parameters: { "settingsParamBundleName": "your app bundlename" }
})
```
## How do I listen for screen rotation events?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Refer to the following code:
```
let listener = mediaquery.matchMediaSync('(orientation: landscape)')
onPortrait(mediaQueryResult) {
if (mediaQueryResult.matches) {
// Do something here.
} else {
// Do something here.
}
}
listener.on('change', onPortrait)
```
## How do I control the shadow background size during checkbox selection?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Set the **padding** attribute of the **\<checkbox>** component to control the shadow size.
## How do I set the widget background to transparent?
Applicable to: OpenHarmony SDK 3.2.5.5
1. Create the **widget/resources/styles/default.json** file in the root directory of the widget.
2. Add the following code to the **default.json** file:
```
{
"style": {
"app_background": "#00000000"
}
}
```
## How do I pass parameters for FA widgets?
Applicable to: OpenHarmony SDK 3.2.5.5
Use **featureAbility.getWant()** and **featureAbility.getContext()** to send data through **router** in the JSON file and use **featureAbility** to receive data in the JS file.
## How do I trigger router.disableAlertBeforeBackPage and router.enableAlertBeforeBackPage?
Applicable to: OpenHarmony SDK 3.2.5.5
The following conditions must be met:
1. Before the redirection to the previous page, a confirm dialog box will be displayed. Note that **router.disableAlertBeforeBackPage** is used to disable the display of a confirm dialog box before returning to the previous page (default), and **router.enableAlertBeforeBackPage** is used to enable the display.
2. The system return key is used.
# Bundle Management Development
## How do I obtain the version code and version name of an application?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Use **bundle.getBundleInfo()** to obtain the bundle information, which contains the version code and version name.
Reference: [Bundle](../reference/apis/js-apis-Bundle.md#bundlegetbundleinfo)
## How do I obtain the bundle name of an application?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Obtain the bundle name through **context.abilityInfo.bundleName**.
Reference: [AbilityContext](../reference/apis/js-apis-ability-context.md) and [AbilityInfo](../reference/apis/js-apis-bundle-AbilityInfo.md)
## How do I obtain an application icon?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Use **bundle.getAbilityIcon** to obtain the application icon. To use this API, you must configure the permission **ohos.permission.GET_BUNDLE_INFO**.
Reference: [Bundle](../reference/apis/js-apis-Bundle.md#bundlegetbundleinfo)
## How do I determine whether an application is a system application?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Use **bundle.getApplicationInfo** to obtain the application information, and then check the value of **systemApp** in the information. The application is a system application if the value is **true**.
# Development Board # Development Board Usage
## How do I take screenshots on a development board? ## How do I take screenshots on a development board?
...@@ -29,8 +27,8 @@ Applicable to: DevEco Studio 3.0.0.991 ...@@ -29,8 +27,8 @@ Applicable to: DevEco Studio 3.0.0.991
1. Create a profile in Previewer. 1. Create a profile in Previewer.
![en-us_image_0000001361254285](figures/en-us_image_0000001361254285.png) ![en-us_image_0000001361254285](figures/en-us_image_0000001361254285.png)
2. Set the profile parameters as follows:
2. Set the profile parameters as follows:
Device type : default Device type : default
Resolution: 720\*1280 Resolution: 720\*1280
......
# Device Management Development # Device Management Development
## How do I obtain the DPI of a device? ## How do I obtain the DPI of a device?
Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
Import the **@ohos.display** module and call the **getDefaultDisplay** API. Import the **\@ohos.display** module and call the **getDefaultDisplay** API.
Example: Example:
...@@ -20,5 +18,33 @@ display.getDefaultDisplay((err, data) => { ...@@ -20,5 +18,33 @@ display.getDefaultDisplay((err, data) => {
} }
console.info('Test Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); console.info('Test Succeeded in obtaining the default display object. Data:' + JSON.stringify(data));
console.info('Test densityDPI:' + JSON.stringify(data.densityDPI)); console.info('Test densityDPI:' + JSON.stringify(data.densityDPI));
});https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-device-info.md) });
``` ```
## How do I obtain the type of the device where the application is running?
Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
Import the **\@ohos.deviceInfo** module and call the **deviceInfo.deviceType** API.
For details, see [Device Information](../reference/apis/js-apis-device-info.md).
## How do I obtain the system version of a device?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Use the **osFullName** attribute of the [deviceInfo](../reference/apis/js-apis-device-info.md) object.
## How do I obtain the UDID of an OpenHarmony device?
Applicable to: OpenHarmony SDK3.0, stage model of API version 9
- To obtain the UDID of the connected device, run the **hdc shell bm get --udid** command.
- For details about how to obtain the UDID from code, see [udid](../reference/apis/js-apis-device-info.md).
## How do I develop a shortcut key function?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
To develop a shortcut key function, use the APIs in [Input Consumer](../reference/apis/js-apis-inputconsumer.md).
...@@ -11,3 +11,80 @@ In effect, the **isStatusBarLightIcon** and **isNavigationBarLightIcon** attribu ...@@ -11,3 +11,80 @@ In effect, the **isStatusBarLightIcon** and **isNavigationBarLightIcon** attribu
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Import the **\@ohos.window** module, and call **window.setSystemBarProperties()**. Import the **\@ohos.window** module, and call **window.setSystemBarProperties()**.
## How do I hide the status bar to get the immersive effect?
Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9
1. Use the **onWindowStageCreate** to obtain a **windowClass** object.
```
onWindowStageCreate(windowStage) {
// When the main window is created, set the main page for this ability.
console.log("[Demo] MainAbility onWindowStageCreate")
windowStage.getMainWindow((err, data) => {
if (err.code) {
console.error('Failed to obtain the main window.')
return;
}
// Obtain a windowClass object.
globalThis.windowClass = data;
})
}
```
2. Enable the full-screen mode for the window and hide the status bar.
```
globalThis.windowClass.setFullScreen(isFullScreen, (err, data) => {
if (err.code) {
console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data));
});
```
## How do I obtain the window width and height?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Use **window.getProperties()** to obtain the window properties. The **windowRect** field in the properties specifies the window width and height.
Example:
```
let promise = windowClass.getProperties();
promise.then((data)=> {
console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data.windowRect));
}).catch((err)=>{
console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err));
});
```
## How do I set the color of the system bar?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Refer to the following code:
```
window.getTopWindow(globalThis.mainContext).then(win => {
var systemBarProperties = {
statusBarColor: '#19B6FF', // Set the background color of the status bar.
navigationBarColor: '#19B6FF', // Set the background color of the navigation bar.
isStatusBarLightIcon: false, // Set the icon on the status bar not to be highlighted.
isNavigationBarLightIcon: true, // Set the icon on the navigation bar to be highlighted.
statusBarContentColor: '#0D0500', // Set the text color of the status bar.
navigationBarContentColor: '#FFA500' // Set the text color of the navigation bar.
};
win.setSystemBarProperties(systemBarProperties).catch(err => {
INDEX_LOGGER.info(`set System Bar Properties failed:${err}`)
})
})
.catch(err => {
INDEX_LOGGER.info(`get top window failed:${err}`)
})
```
# Media Development
## How do I set a front camera?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
1. Set the camera position to **camera.CameraPosition.CAMERA_POSITION_FRONT**.
2. Create a **CameraInput** instance based on the camera position and type.
Reference: [Camera Management](../reference/apis/js-apis-camera.md)
Example:
```
// The rear camera is set by default. You can use **isFrontCamera** to switch to the rear camera.
let cameraId
let cameraInput
for(let cameraIndex = 0; cameraIndex < this.cameraArray.length; cameraIndex++) {
let faceType = this.cameraArray[cameraIndex].cameraPosition
switch(faceType) {
case camera.CameraPosition.CAMERA_POSITION_FRONT: // Front camera
if(this.isFrontCamera){
cameraId = this.cameraArray[cameraIndex].cameraId
}
break
case camera.CameraPosition.CAMERA_POSITION_BACK: // Rear camera
if(!this.isFrontCamera){
cameraId = this.cameraArray[cameraIndex].cameraId
}
break
case camera.CameraPosition.CAMERA_POSITION_UNSPECIFIED:
default:
break
}
}
cameraInput = await this.cameraManager.createCameraInput(cameraId)
```
## How do I crop an image?
Applicable to: OpenHarmony SDK 3.2.5.6, stage model of API version 9
1. Create an **ImageSource** instance based on the input URI.
```
let path = this.context.getApplicationContext().fileDirs + "test.jpg";
const imageSourceApi = image.createImageSource(path);
```
2. Set decoding parameters and decode the image to obtain a **PixelMap** object. Image processing is supported during decoding.
- Set **desiredSize** to specify the target size after scaling. If the values are all set to **0**, scaling will not be performed.
- Set **desiredRegion** to specify the target rectangular area after cropping. If the values are all set to **0**, cropping will not be performed.
- Set **rotateDegrees** to specify the rotation angle. The image will be rotated clockwise at the center.
```
const decodingOptions = {
desiredSize: {
height:0,
width:0
},
// Crop a rectangular area.
desiredRegion: {
size: {
height:100,
width:100
},
x:0,
y:0
},
// Rotate the image by 90 degrees.
rotate:90
}
imageSourceApi.createPixelMap(decodingOptions).then(pixelMap => {
this.handlePixelMap(pixelMap)
})
```
3. Process the obtained **PixelMap** object. For example, render and display the image.
## How do I apply for the media read/write permission on a device?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
1. Configure the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA** in the **module.json5** file.
Example:
```
{
"module" : {
"requestPermissions":[
{
"name" : "ohos.permission.READ_MEDIA",
"reason": "$string:reason"
},
{
"name" : "ohos.permission.WRITE_MEDIA",
"reason": "$string:reason"
}
]
}
}
```
2. Call **requestPermissionsFromUser** to request the permissions from end users in the form of a dialog box. This operation is required because the grant mode of both permissions is **user_grant**.
```
let permissions: Array<string> = ['ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA']
context.requestPermissionsFromUser(permissions).then((data) => {
console.log("Succeed to request permission from user with data: " + JSON.stringify(data))
}).catch((error) => {
console.log("Failed to request permission from user with error: " + JSON.stringify(error))
})
```
## Why can't I play MP4 videos?
Applicable to: OpenHarmony SDK 3.2.7.5, stage model of API version 9
Currently, the system does not support the playback of MP4 videos in H.265 format.
## Why can't I play a new video or even encounters a crash after creating more than 10 videos?
Applicable to: OpenHarmony SDK 3.2.7.5, stage model of API version 9
A maximum of 13 media player instances can be created.
# Native API Usage # Native API Usage
## Is there a native API that provides functions similar to Canvas?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
Yes. The native API **Drawing** provides similar functions. It can be used for 2D drawing.
## When a native HAP is running, the error message "Obj is not a valid object" is displayed for the imported namespace. What should I do? ## When a native HAP is running, the error message "Obj is not a valid object" is displayed for the imported namespace. What should I do?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
Check the **abiFilters** parameter value in the **build-profile.json5** file in the root directory of the module (not the root directory of the project). If the device is 32-bit, the value must be **armeabi-v7a**. If the device is 64-bit, the value must be **arm64-v8a**. Check the **abiFilters** parameter value in the **build-profile.json5** file in the root directory of the module (not the root directory of the project). If the device is 32-bit, the value must be **armeabi-v7a**. If the device is 64-bit, the value must be **arm64-v8a**.
## How do I obtain the value of version in the package.json file of a module in the C++ code developed using native APIs? ## What should I do when the error message "install parse profile prop check error" is displayed during the running of a native HAP?
Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9
Check the **abiFilters** parameter value in the **build-profile.json5** file in the root directory of the module (not the root directory of the project). If the device is 32-bit, the value must be **armeabi-v7a**. If the device is 64-bit, the value must be **arm64-v8a**.
## What should I do when the error message "undefined symbol: OH_LOG_Print" is displayed during log printing by **OH_LOG_Print**?
Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9
Modify the **CMakeLists.txt** file by adding **libhilog_ndk.z.so** to the end of **target_link_libraries**.
## How do I obtain the value of version in the package.json file of a module?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
...@@ -53,3 +71,9 @@ static napi_value Add(napi_env env, napi_callback_info info) ...@@ -53,3 +71,9 @@ static napi_value Add(napi_env env, napi_callback_info info)
return fixed_version_value; return fixed_version_value;
} }
``` ```
## How do I traverse files in rawfile?
Applicable to: OpenHarmony SDK 3.2 or later, stage model of API version 9
Use the native API **OH_ResourceManager_OpenRawDir()** to obtain the root directory of **rawfile** and traverse the root directory.
# Usage of Third- and Fourth-Party Libraries # Usage of Third- and Fourth-Party Libraries
## What does the following error message mean : "Stage model module... does not support including OpenHarmony npm packages or modules in FA model. OpenHarmony build tasks will not be executed, and OpenHarmony resources will not be packed." ## What does the following error message mean: "Stage model module... does not support including OpenHarmony npm packages or modules in FA model. OpenHarmony build tasks will not be executed, and OpenHarmony resources will not be packed."
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
The third- and fourth-party libraries are not yet compatible with the stage model of API version 9 and cannot be used. The third- and fourth-party libraries are not yet compatible with the stage model of API version 9 and cannot be used.
## Can I transfer project-level dependencies?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
For example, if project A depends on project B and project B depends on project C, can project A directly use the APIs provided by project C?
No. Project A cannot directly use the APIs provided by project C. The project packing tool NPM does not support dependency transfer. To use the APIs provided by project C, you can add the dependency of project C to project A.
## How do I obtain available third-party libraries?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
For details, see [Third-Party Components That Can Be Directly Used on OpenHarmony](https://gitee.com/openharmony-sig/third_party_app_libs).
## Which third-party libraries are related to network requests?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
The [Axios](https://gitee.com/openharmony-sig/axios) library is related to network requests.
## How do I use NPM to import third- and fourth-party libraries?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
- Method 1:
1. Open the **Terminal** window and run the following command to go to the **entry** directory:
```
cd entry
```
2. Run the following command to install a third-party package, for example, **dayjs**:
```
npm install dayjs --save
```
3. Add the following statement in the .js file to import the package:
```
import dayjs from 'dayjs';
```
- Method 2:
1. Enter the **entry** directory of the project and open the **package.json** file.
2. Write the third-party NPM package to be installed (for example, **dayjs**) in the **package.json** file.
```
{
"dependencies": {
"dayjs": "^1.10.4",
}
}
```
3. Open the **Terminal** window and run the following command to go to the **entry** directory:
```
cd entry
```
4. Run the following command to install NPM:
```
npm install
```
5. Add the following statement in the .js file to import the package:
```
import dayjs from 'dayjs';
```
# ArkUI (eTS) Development # ArkUI (ArkTS) Development
...@@ -72,7 +72,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 ...@@ -72,7 +72,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
2. Convert data in Uint8Array format to the string type by calling the **String.fromCharCode** API. 2. Convert data in Uint8Array format to the string type by calling the **String.fromCharCode** API.
Reference: [Resource Management](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-resource-manager.md) Reference: [Resource Management](../reference/apis/js-apis-resource-manager.md)
Example: Example:
...@@ -94,7 +94,7 @@ Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 ...@@ -94,7 +94,7 @@ Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Use the **resourceManager.getString()** API of the **\@ohos.resourceManager** module. Use the **resourceManager.getString()** API of the **\@ohos.resourceManager** module.
Reference: [Resource Management](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-resource-manager.md#getstring) Reference: [Resource Management](../reference/apis/js-apis-resource-manager.md#getstring)
## What should I do if the global static variables of a class do not work? ## What should I do if the global static variables of a class do not work?
...@@ -102,8 +102,6 @@ Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 ...@@ -102,8 +102,6 @@ Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Objects imported to abilities and pages are packaged into two different closures, that is, two global objects. In this case, a static variable referenced by the abilities is not the same object as that referenced by the pages. Therefore, global variables cannot be defined by defining static variables in the class. You are advised to use AppStorage to manage global variables. Objects imported to abilities and pages are packaged into two different closures, that is, two global objects. In this case, a static variable referenced by the abilities is not the same object as that referenced by the pages. Therefore, global variables cannot be defined by defining static variables in the class. You are advised to use AppStorage to manage global variables.
Reference: [AppStorage](https://docs.openharmony.cn/pages/v3.2Beta/en/application-dev/ui/ts-application-states-appstorage.md/)
## How do I obtain resources in the stage model? ## How do I obtain resources in the stage model?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
...@@ -154,9 +152,9 @@ build() { ...@@ -154,9 +152,9 @@ build() {
Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
No. Currently, **CustomDialog** can be used only on eTS pages. No. Currently, **CustomDialog** can be used only on ArkTS pages.
Reference: [Custom Dialog Box](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md) Reference: [Custom Dialog Box](../reference/arkui-ts/ts-methods-custom-dialog-box.md)
## How do I transfer variables in CustomDialog to variables on pages? ## How do I transfer variables in CustomDialog to variables on pages?
...@@ -210,7 +208,7 @@ Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 ...@@ -210,7 +208,7 @@ Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
By default, child components in a **\<GridContainer>** are horizontally aligned to the left. To center them, perform the following steps: By default, child components in a **\<GridContainer>** are horizontally aligned to the left. To center them, perform the following steps:
Nest a **\<Row>** component and set it to **justifyContent(FlexAlign.Center)**. For details, see [Grid Layout](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/ui/ui-ts-layout-grid-container.md). Nest a **\<Row>** component and set it to **justifyContent(FlexAlign.Center)**. For details, see [Grid Layout](../reference/arkui-ts/ts-container-gridcontainer.md).
Example: Example:
...@@ -267,13 +265,13 @@ export default class MainAbility extends Ability { ...@@ -267,13 +265,13 @@ export default class MainAbility extends Ability {
} }
``` ```
## How do I execute JavaScript functions in the \<Web> component in eTS code? ## How do I execute JavaScript functions in the \<Web> component in ArkTS code?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Call the **runJavaScript** API in the **WebController** to asynchronously execute JavaScript scripts. This API uses a callback to return the execution result. Note: **runJavaScript** can only be called after **loadUrl** has been completed. For example, it can be called in **onPageEnd**. Call the **runJavaScript** API in the **WebController** to asynchronously execute JavaScript scripts. This API uses a callback to return the execution result. Note: **runJavaScript** can only be called after **loadUrl** has been completed. For example, it can be called in **onPageEnd**.
Reference: [Web](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/arkui-ts/ts-basic-components-web.md) Reference: [Web](../reference/arkui-ts/ts-basic-components-web.md)
## How do I fix misidentification of the pan gesture where container nesting is involved? ## How do I fix misidentification of the pan gesture where container nesting is involved?
......
# ArkUI (JavaScript) Development # ArkUI (JavaScript) Development
## How do I convert the fields in an XML file into JavaScript objects? ## How do I convert the fields in an XML file into JavaScript objects?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
...@@ -13,8 +11,8 @@ Example: ...@@ -13,8 +11,8 @@ Example:
``` ```
import convertxml from '@ohos.convertxml'; import convertxml from '@ohos.convertxml';
// Code snippet // XML strings
xml = let xml =
'<?xml version="1.0" encoding="utf-8"?>' + '<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' + '<note importance="high" logged="true">' +
' <title>Happy</title>' + ' <title>Happy</title>' +
...@@ -23,28 +21,27 @@ xml = ...@@ -23,28 +21,27 @@ xml =
'</note>'; '</note>';
let conv = new convertxml.ConvertXML(); let conv = new convertxml.ConvertXML();
// Options for conversion. For details, see the reference document. // Options for conversion. For details, see the reference document.
let options = {trim : false, declarationKey:"_declaration", let options = {
instructionKey : "_instruction", attributesKey : "_attributes", trim: false,
textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype", declarationKey: "_declaration",
commentKey : "_comment", parentKey : "_parent", typeKey : "_type", instructionKey: "_instruction",
nameKey : "_name", elementsKey : "_elements"} attributesKey: "_attributes",
let result:any = conv.convert(xml, options) // Convert fields in the XML file into JavaScript objects. textKey: "_text",
cdataKey: "_cdata",
doctypeKey: "_doctype",
commentKey: "_comment",
parentKey: "_parent",
typeKey: "_type",
nameKey: "_name",
elementsKey: "_elements"
}
let result: any = conv.convert(xml, options) // Convert fields in the XML file into JavaScript objects.
console.log('Test: ' + JSON.stringify(result)) console.log('Test: ' + JSON.stringify(result))
console.log('Test: ' + result._declaration._attributes.version) // version field in XML file console.log('Test: ' + result._declaration._attributes.version) // version field in the XML file
console.log('Test: ' + result._elements[0]._elements[0]._elements[0]._text) // title field in XML file console.log('Test: ' + result._elements[0]._elements[0]._elements[0]._text) // title field in the XML file
``` ```
Reference: [XML-to-JavaScript Conversion](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-convertxml.md) For details, see [XML-to-JavaScript Conversion](../reference/apis/js-apis-convertxml.md).
## What are the differences between JavaScript, TypeScript, and eTS?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
- JavaScript: a lightweight, weakly-typed programming language, most commonly known as the scripting language for web pages.
- TypeScript: a superset of JavaScript, with additions of static typing and more object-oriented APIs, enums, etc.
- eTS: a superset of TypeScript and the programming language for OpenHarmony ArkUI development, which powers UI development through a declarative development paradigm.
## How do I convert the time to the HHMMSS format? ## How do I convert the time to the HHMMSS format?
...@@ -93,4 +90,5 @@ export default class DateTimeUtil{ ...@@ -93,4 +90,5 @@ export default class DateTimeUtil{
return `${this.fill(hours)}${this.fill(minutes)}${this.fill(seconds)}` return `${this.fill(hours)}${this.fill(minutes)}${this.fill(seconds)}`
} }
} }
``` ```
...@@ -12,9 +12,9 @@ To ensure the application running efficiency, most **MediaLibrary** API calls ar ...@@ -12,9 +12,9 @@ To ensure the application running efficiency, most **MediaLibrary** API calls ar
You can obtain images and videos in an album in either of the following ways: You can obtain images and videos in an album in either of the following ways:
- Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified to obtain the media assets. For details, see [Querying Media Assets with the Specified Album Name](medialibrary-resource-guidelines#querying-media-assets-with-the-specified-album-name). - Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified to obtain the media assets. For details, see [Querying Media Assets with the Specified Album Name](medialibrary-resource-guidelines.md#querying-media-assets-with-the-specified-album-name).
- Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it. For details, see [Obtaining Images and Videos in an Album](medialibrary-resource-guidelines#obtaining-images-and-videos-in-an-album). - Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it. For details, see [Obtaining Images and Videos in an Album](medialibrary-resource-guidelines.md#obtaining-images-and-videos-in-an-album).
## Creating an Album ## Creating an Album
......
...@@ -6,7 +6,7 @@ Your applications can use the APIs provided by the **mediaLibrary** module to pe ...@@ -6,7 +6,7 @@ Your applications can use the APIs provided by the **mediaLibrary** module to pe
> >
> Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**. > Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**.
To ensure the application running efficiency, most **MediaLibrary** API calls are asynchronous, and both callback and promise modes are provided for these APIs. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md). To maximize the application running efficiency, most **MediaLibrary** API calls are asynchronous in callback or promise mode. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md).
## Querying Media Assets ## Querying Media Assets
...@@ -215,7 +215,7 @@ async function getCameraImagePromise() { ...@@ -215,7 +215,7 @@ async function getCameraImagePromise() {
## Obtaining the Thumbnail of an Image or a Video ## Obtaining the Thumbnail of an Image or a Video
You can call [FileAsset.getThumbnail](../reference/apis/js-apis-medialibrary.md#getthumbnail8-2) with the thumbnail size passed in to obtain the thumbnail of an image or a video. Thumbnails are usually displayed on the UI. You can call [FileAsset.getThumbnail](../reference/apis/js-apis-medialibrary.md#getthumbnail8-2) with the thumbnail size passed in to obtain the thumbnail of an image or a video. Your application can use thumbnails to offer a quick preview on images and videos.
**Prerequisites** **Prerequisites**
...@@ -224,8 +224,6 @@ You can call [FileAsset.getThumbnail](../reference/apis/js-apis-medialibrary.md# ...@@ -224,8 +224,6 @@ You can call [FileAsset.getThumbnail](../reference/apis/js-apis-medialibrary.md#
### Obtaining the Thumbnail of an Image ### Obtaining the Thumbnail of an Image
Your application may need to obtain the thumbnail of an image for preview purposes.
The following describes how to obtain the thumbnail (size: 720 x 720) of the first image in the album. The following describes how to obtain the thumbnail (size: 720 x 720) of the first image in the album.
**How to Develop** **How to Develop**
...@@ -273,7 +271,7 @@ You can call [MediaLibrary.createAsset](../reference/apis/js-apis-medialibrary.m ...@@ -273,7 +271,7 @@ You can call [MediaLibrary.createAsset](../reference/apis/js-apis-medialibrary.m
- You have obtained a **MediaLibrary** instance. - You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**. - You have granted the permission **ohos.permission.WRITE_MEDIA**.
- [Obtain the public directory](medialibrary-filepath-guidelines.md). - [You have obtained a public directory](medialibrary-filepath-guidelines.md).
The following describes how to create a file of the **MediaType.FILE** type. The following describes how to create a file of the **MediaType.FILE** type.
...@@ -296,7 +294,7 @@ async function example() { ...@@ -296,7 +294,7 @@ async function example() {
You can use [FileAsset.trash](../reference/apis/js-apis-medialibrary.md#trash8) to move a media asset to the recycle bin. You can use [FileAsset.trash](../reference/apis/js-apis-medialibrary.md#trash8) to move a media asset to the recycle bin.
By default, files in the recycle bin will be stored for 30 days. During this period, you can set **isTrash** in **trash** to **false** to recover the files from the recycle bin. Application users can also recover the files through the system applications **Files** or **Gallery**. By default, files in the recycle bin will be stored for 30 days before being permanently removed. During this period, you can set **isTrash** in **trash** to **false** to recover the files. Application users can also recover the files through the system applications **Files** or **Gallery**.
**Prerequisites** **Prerequisites**
...@@ -339,11 +337,9 @@ async function example() { ...@@ -339,11 +337,9 @@ async function example() {
## Renaming a Media Asset ## Renaming a Media Asset
Renaming modifies the **FileAsset.displayName** attribute of a file, that is, the displayed file name, including the file name extension. To rename a media asset, modify the **FileAsset.displayName** attribute (which specifies the displayed file name, including the file name extension) and commit the modification through [FileAsset.commitModify](../reference/apis/js-apis-medialibrary.md#commitmodify8-1).
After the modification, call [FileAsset.commitModify](../reference/apis/js-apis-medialibrary.md#commitmodify8-1) to commit the modification to the database.
Before renaming a file, you must call [FetchFileResult](../reference/apis/js-apis-medialibrary.md#fetchfileresult7) to obtain the file. Before renaming a file, you must obtain the file, for example, by calling [FetchFileResult](../reference/apis/js-apis-medialibrary.md#fetchfileresult7).
**Prerequisites** **Prerequisites**
...@@ -358,7 +354,7 @@ The following describes how to rename the first file in the result set as **newt ...@@ -358,7 +354,7 @@ The following describes how to rename the first file in the result set as **newt
2. Call **getFileAssets** to obtain the images in the target album. 2. Call **getFileAssets** to obtain the images in the target album.
3. Call **getFirstObject** to obtain the first image among all the images obtained. 3. Call **getFirstObject** to obtain the first image among all the images obtained.
4. Rename the image as **newImage.jpg**. 4. Rename the image as **newImage.jpg**.
5. Call **FileAsset.commitModify** to commit the modification of the attributes to the database. 5. Call **FileAsset.commitModify** to commit the modification to the database.
```ts ```ts
async function example() { async function example() {
......
...@@ -10,11 +10,16 @@ ...@@ -10,11 +10,16 @@
- [OpenSL ES Audio Playback Development](opensles-playback.md) - [OpenSL ES Audio Playback Development](opensles-playback.md)
- [OpenSL ES Audio Recording Development](opensles-capture.md) - [OpenSL ES Audio Recording Development](opensles-capture.md)
- [Audio Interruption Mode Development](audio-interruptmode.md) - [Audio Interruption Mode Development](audio-interruptmode.md)
- [Volume Management Development](audio-volume-manager.md)
- [Audio Routing and Device Management Development](audio-routing-manager.md)
- Video - Video
- [Video Playback Development](video-playback.md) - [Video Playback Development](video-playback.md)
- [Video Recording Development](video-recorder.md) - [Video Recording Development](video-recorder.md)
- AVSession
- [AVSession Overview](avsession-overview.md)
- [AVSession Development](avsession-guidelines.md)
- Image - Image
- [Image Development](image.md) - [Image Development](image.md)
......
...@@ -2,11 +2,11 @@ ...@@ -2,11 +2,11 @@
## Introduction ## Introduction
You can use audio playback APIs to convert audio data into audible analog signals and play the signals using output devices. You can also manage playback tasks. For example, you can start, suspend, stop playback, release resources, set the volume, seek to a playback position, and obtain track information. You can use audio playback APIs to convert audio data into audible analog signals and play the signals using output devices. You can also manage playback tasks. For example, you can control the playback and volume, obtain track information, and release resources.
## Working Principles ## Working Principles
The following figures show the audio playback status changes and the interaction with external modules for audio playback. The following figures show the audio playback state transition and the interaction with external modules for audio playback.
**Figure 1** Audio playback state transition **Figure 1** Audio playback state transition
...@@ -28,7 +28,7 @@ For details about the APIs, see [AudioPlayer in the Media API](../reference/apis ...@@ -28,7 +28,7 @@ For details about the APIs, see [AudioPlayer in the Media API](../reference/apis
> **NOTE** > **NOTE**
> >
> The method for obtaining the path in the FA model is different from that in the stage model. **pathDir** used in the sample code below is an example. You need to obtain the path based on project requirements. For details about how to obtain the path, see [Application Sandbox Path Guidelines](../reference/apis/js-apis-fileio.md#guidelines). > The method for obtaining the path in the FA model is different from that in the stage model. For details about how to obtain the path, see [Application Sandbox Path Guidelines](../reference/apis/js-apis-fileio.md#guidelines).
### Full-Process Scenario ### Full-Process Scenario
...@@ -109,7 +109,7 @@ async function audioPlayerDemo() { ...@@ -109,7 +109,7 @@ async function audioPlayerDemo() {
setCallBack(audioPlayer); // Set the event callbacks. setCallBack(audioPlayer); // Set the event callbacks.
// 2. Set the URI of the audio file. // 2. Set the URI of the audio file.
let fdPath = 'fd://' let fdPath = 'fd://'
let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3' let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => { await fileIO.open(path).then((fdNumber) => {
...@@ -151,7 +151,7 @@ export class AudioDemo { ...@@ -151,7 +151,7 @@ export class AudioDemo {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks. this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://' let fdPath = 'fd://'
let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3' let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => { await fileIO.open(path).then((fdNumber) => {
...@@ -199,7 +199,7 @@ export class AudioDemo { ...@@ -199,7 +199,7 @@ export class AudioDemo {
async nextMusic(audioPlayer) { async nextMusic(audioPlayer) {
this.isNextMusic = true; this.isNextMusic = true;
let nextFdPath = 'fd://' let nextFdPath = 'fd://'
let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let nextpath = pathDir + '/02.mp3' let nextpath = pathDir + '/02.mp3'
await fileIO.open(nextpath).then((fdNumber) => { await fileIO.open(nextpath).then((fdNumber) => {
...@@ -217,7 +217,7 @@ export class AudioDemo { ...@@ -217,7 +217,7 @@ export class AudioDemo {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks. this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://' let fdPath = 'fd://'
let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3' let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => { await fileIO.open(path).then((fdNumber) => {
...@@ -256,7 +256,7 @@ export class AudioDemo { ...@@ -256,7 +256,7 @@ export class AudioDemo {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks. this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://' let fdPath = 'fd://'
let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3' let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => { await fileIO.open(path).then((fdNumber) => {
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
The Native Drawing module provides APIs for drawing 2D graphics and text. The following scenarios are common for drawing development: The Native Drawing module provides APIs for drawing 2D graphics and text. The following scenarios are common for drawing development:
* Drawing 2D graphics * Drawing 2D graphics
* Drawing and painting text * Drawing text drawing
## Available APIs ## Available APIs
...@@ -19,7 +19,7 @@ The Native Drawing module provides APIs for drawing 2D graphics and text. The fo ...@@ -19,7 +19,7 @@ The Native Drawing module provides APIs for drawing 2D graphics and text. The fo
| OH_Drawing_CanvasDrawPath (OH_Drawing_Canvas *, const OH_Drawing_Path *) | Draws a path.| | OH_Drawing_CanvasDrawPath (OH_Drawing_Canvas *, const OH_Drawing_Path *) | Draws a path.|
| OH_Drawing_PathCreate (void) | Creates a path object.| | 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_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_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_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_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_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.|
...@@ -138,7 +138,7 @@ The following steps describe how to use the canvas and brush of the Native Drawi ...@@ -138,7 +138,7 @@ The following steps describe how to use the canvas and brush of the Native Drawi
OH_Drawing_BitmapDestory(cBitmap); OH_Drawing_BitmapDestory(cBitmap);
``` ```
## Development Procedure for Text Drawing and Display ## Development Procedure for Text Drawing
The following steps describe how to use the text drawing and display feature of the Native Drawing module. 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.** 1. **Create a canvas and a bitmap.**
...@@ -196,7 +196,8 @@ The following steps describe how to use the text drawing and display feature of ...@@ -196,7 +196,8 @@ The following steps describe how to use the text drawing and display feature of
// Set the maximum width. // Set the maximum width.
double maxWidth = 800.0; double maxWidth = 800.0;
OH_Drawing_TypographyLayout(typography, maxWidth); OH_Drawing_TypographyLayout(typography, maxWidth);
// Set the start position for text display. // Set the start position for drawing the text on the canvas.
double position[2] = {10.0, 15.0}; double position[2] = {10.0, 15.0};
// Draw the text on the canvas.
OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]); OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]);
``` ```
此差异已折叠。
...@@ -13,4 +13,4 @@ HUAWEI DevEco Studio For OpenHarmony (DevEco Studio for short) is a one-stop int ...@@ -13,4 +13,4 @@ HUAWEI DevEco Studio For OpenHarmony (DevEco Studio for short) is a one-stop int
- **One-stop information acquisition**: A one-stop information acquisition platform that takes into account the developer journey of learning, development, and help seeking, in order to facilitate developer activities. - **One-stop information acquisition**: A one-stop information acquisition platform that takes into account the developer journey of learning, development, and help seeking, in order to facilitate developer activities.
- **Efficient code debugging**: Various debugging capabilities such as TS, JS, and C/C++ code breakpoint setting, single-step execution, and variable viewing, improving the efficiency of analyzing application/service issues. - **Efficient code debugging**: Various debugging capabilities such as TS, JS, and C/C++ code breakpoint setting, single-step execution, and variable viewing, improving the efficiency of analyzing application/service issues.
For more information, see [DevEco Studio (OpenHarmony) User Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-deveco-studio-overview-0000001263280421). For more information, see [DevEco Studio User Guide (OpenHarmony)](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-deveco-studio-overview-0000001263280421).
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册