“37f4867b7a04d5a365f4453d5baec4ce6552af41”上不存在“src/share/classes/java/nio/Heap-X-Buffer.java.template”
提交 6f729a0a 编写于 作者: C chensi10

Merge branch 'master' of https://gitee.com/openharmony/docs into radio

Signed-off-by: Nchensi10 <chensi52@huawei.com>
...@@ -18,7 +18,7 @@ This repository stores device and application development documents provided by ...@@ -18,7 +18,7 @@ This repository stores device and application development documents provided by
- master: the latest version. - master: the latest version.
- OpenHarmony 3.2 Beta3. [Learn more](en/release-notes/OpenHarmony-v3.2-beta3.md) - OpenHarmony 3.2 Beta5. [Learn more](en/release-notes/OpenHarmony-v3.2-beta5.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)
...@@ -34,7 +34,7 @@ This repository stores device and application development documents provided by ...@@ -34,7 +34,7 @@ This repository stores device and application development documents provided by
### Historical Stable Versions ### Historical Stable Versions
OpenHarmony_v1.x_release: OpenHarmony v1.1.5 LTS. [Learn more](en/release-notes/OpenHarmony-v1.1.5-LTS.md) OpenHarmony_v1.x_release: OpenHarmony 1.1.5 LTS. [Learn more](en/release-notes/OpenHarmony-v1.1.5-LTS.md)
[More versions](en/release-notes/) [More versions](en/release-notes/)
...@@ -51,6 +51,6 @@ You can evaluate available documents, make simple modifications, provide feedbac ...@@ -51,6 +51,6 @@ You can evaluate available documents, make simple modifications, provide feedbac
Excellent contributors will be awarded and the contributions will be publicized in the developer community. Excellent contributors will be awarded and the contributions will be publicized in the developer community.
- Mail list: docs@openharmony.io - Mailing list: docs@openharmony.io
- Zulip group: documentation_sig - Zulip group: documentation_sig
\ No newline at end of file
...@@ -183,7 +183,7 @@ For details about how to obtain the source code of OpenHarmony, see [Source Code ...@@ -183,7 +183,7 @@ For details about how to obtain the source code of OpenHarmony, see [Source Code
## Hands-On Tutorials ## Hands-On Tutorials
[Samples](https://gitee.com/openharmony/app_samples) [Samples](https://gitee.com/openharmony/applications_app_samples)
[Codelabs](https://gitee.com/openharmony/codelabs) [Codelabs](https://gitee.com/openharmony/codelabs)
......
...@@ -24,7 +24,7 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O ...@@ -24,7 +24,7 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O
All applications should be developed on top of these frameworks. All applications should be developed on top of these frameworks.
Then, equip yourself for developing the key features, with the following guidelines: Then, equip yourself for developing the key features, with the following guidelines:
- [Common Event and Notification](notification/notification-brief.md) - [Common Event and Notification](notification/notification-overview.md)
- [Window Manager](windowmanager/window-overview.md) - [Window Manager](windowmanager/window-overview.md)
- [WebGL](webgl/webgl-overview.md) - [WebGL](webgl/webgl-overview.md)
- [Media](media/audio-overview.md) - [Media](media/audio-overview.md)
......
...@@ -17,8 +17,11 @@ ...@@ -17,8 +17,11 @@
- ExtensionAbility Component - ExtensionAbility Component
- [ExtensionAbility Component Overview](extensionability-overview.md) - [ExtensionAbility Component Overview](extensionability-overview.md)
- [ServiceExtensionAbility](serviceextensionability.md) - [ServiceExtensionAbility](serviceextensionability.md)
- [DataShareExtensionAbility](datashareextensionability.md) - [DataShareExtensionAbility (System Applications Only)](datashareextensionability.md)
- [FormExtensionAbility (Widget)](widget-development-stage.md) - [FormExtensionAbility (Widget)](widget-development-stage.md)
- [StaticSubscriberExtensionAbility](static-subscriber-extension-ability.md)
- [AccessibilityExtensionAbility](accessibilityextensionability.md)
- [WindowExtensionAbility](windowextensionability.md)
- [AbilityStage Component Container](abilitystage.md) - [AbilityStage Component Container](abilitystage.md)
- [Context](application-context-stage.md) - [Context](application-context-stage.md)
- Want - Want
...@@ -31,8 +34,8 @@ ...@@ -31,8 +34,8 @@
- [Component Startup Rules](component-startup-rules.md) - [Component Startup Rules](component-startup-rules.md)
- Inter-Device Application Component Interaction (Continuation) - Inter-Device Application Component Interaction (Continuation)
- [Continuation Overview](inter-device-interaction-hop-overview.md) - [Continuation Overview](inter-device-interaction-hop-overview.md)
- [Cross-Device Migration](hop-cross-device-migration.md) - [Cross-Device Migration (System Applications Only)](hop-cross-device-migration.md)
- [Multi-device Collaboration](hop-multi-device-collaboration.md) - [Multi-device Collaboration (System Applications Only)](hop-multi-device-collaboration.md)
- IPC - IPC
- [Process Model](process-model-stage.md) - [Process Model](process-model-stage.md)
- Common Events - Common Events
...@@ -62,7 +65,7 @@ ...@@ -62,7 +65,7 @@
- [Creating a PageAbility](create-pageability.md) - [Creating a PageAbility](create-pageability.md)
- [Starting a Local PageAbility](start-local-pageability.md) - [Starting a Local PageAbility](start-local-pageability.md)
- [Stopping a PageAbility](stop-pageability.md) - [Stopping a PageAbility](stop-pageability.md)
- [Starting a Remote PageAbility](start-remote-pageability.md) - [Starting a Remote PageAbility (System Applications Only)](start-remote-pageability.md)
- [Starting a Specified Page](start-page.md) - [Starting a Specified Page](start-page.md)
- [Window Properties](window-properties.md) - [Window Properties](window-properties.md)
- [Requesting Permissions](request-permissions.md) - [Requesting Permissions](request-permissions.md)
......
# AccessibilityExtensionAbility Development
The **AccessibilityExtensionAbility** module provides accessibility extension capabilities based on the **ExtensionAbility** framework. You can develop your accessibility applications by applying the **AccessibilityExtensionAbility** template to enhance usability.
> **Environment Requirements**
>
> IDE: DevEco Studio 3.0 Beta3 (3.0.0.900) or later
>
> SDK: API version 9 or later
>
> Model: stage
This document is organized as follows:
- [Creating an AccessibilityExtAbility File](#creating-an-accessibility-extension-service)
- [Processing an Accessibility Event](#processing-an-accessibility-event)
- [Declaring Capabilities of Accessibility Extension Services](#declaring-capabilities-of-accessibility-extension-services)
- [Enabling a Custom Accessibility Extension Service](#enabling-a-custom-accessibility-extension-service)
## Creating an Accessibility Extension Service
You can create an accessibility extension service by creating a project from scratch or adding the service to an existing project.
### Creating a Project
Perform the following steps in DevEco Studio:
1. From the upper left corner of DevEco Studio, choose **File** > **New** > **Create Project**.
2. By following the project creation wizard, click the **OpenHarmony** tab, select the **Empty Ability** template, and then click **Next**.
3. Set **Project type** to **Application**, **Compile API** (or **Compile SDK**, depending on the version used) to **9**, and **Model** to **Stage**, and then click **Finish**.
### Creating an AccessibilityExtAbility File
To add an accessibility extension service to a project, create the **AccessibilityExtAbility** folder in the **ets** folder of the project, create the **AccessibilityExtAbility.ts** file in the new folder, and add the following code to the new file:
```typescript
import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility';
class AccessibilityExtAbility extends AccessibilityExtensionAbility {
onConnect() {
console.log('AccessibilityExtAbility onConnect');
}
onDisconnect() {
console.log('AccessibilityExtAbility onDisconnect');
}
onAccessibilityEvent(accessibilityEvent) {
console.log('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent));
}
}
export default AccessibilityExtAbility;
```
The APIs defined in the file are as follows.
| API| Description|
| ---- | ---- |
| onConnect(): void | Called when a connection with the extension service is set up.|
| onDisconnect(): void | Called when the connection with the extension service is severed.|
| onAccessibilityEvent(event: AccessibilityEvent): void | Called when an accessibility event occurs|
## Processing an Accessibility Event
You can process the service logic for accessibility events in the **onAccessibilityEvent()** API. For details about the events, see [AccessibilityEvent](../reference/apis/js-apis-application-accessibilityExtensionAbility.md#accessibilityevent). The following code snippet uses the **pageStateUpdate** event as an example.
```typescript
onAccessibilityEvent(accessibilityEvent) {
console.log('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent));
if (accessibilityEvent.eventType === 'pageStateUpdate') {
console.log('AccessibilityExtAbility onAccessibilityEvent: pageStateUpdate');
// TODO: Develop custom logic.
}
}
```
For an accessibility event, you can use the APIs of the [AccessibilityExtensionContext](../reference/apis/js-apis-inner-application-accessibilityExtensionContext.md) module to configure the concerned information, obtain root information, and inject gestures.
You can also process physical key events in the accessibility extension service. For details, see [onKeyEvent](../reference/apis/js-apis-application-accessibilityExtensionAbility.md#accessibilityextensionabilityonkeyevent).
## Declaring Capabilities of Accessibility Extension Services
After developing the custom logic for an accessibility extension service, you must add the configuration information of the service to the corresponding module-level **module.json5** file in the project directory. In the file, the **srcEntrance** tag indicates the path to the accessibility extension service. Make sure the value of the **type** tag is fixed at **accessibility**. Otherwise, the connection to the service will fail.
```json
"extensionAbilities": [
{
"name": "AccessibilityExtAbility",
"srcEntrance": "./ets/AccessibilityExtAbility/AccessibilityExtAbility.ts",
"label": "$string:MainAbility_label",
"description": "$string:MainAbility_desc",
"type": "accessibility",
"metadata": [
{
"name": "ohos.accessibleability",
"resource": "$profile:accessibility_config"
}
]
}
]
```
**accessibility_config** is the specific configuration of the accessibility extension service. You need to create the **accessibility_config.json** file in **resources/base/profile/** and declare the [capabilities](../reference/apis/js-apis-accessibility.md#capability) of the service in the file.
```json
{
"accessibilityCapabilities": [
"retrieve",
"gesture"
]
}
```
## Enabling a Custom Accessibility Extension Service
To enable or disable an accessibility extension service, run the following command:
- To enable the service: **accessibility enable -a AccessibilityExtAbility -b com.example.demo -c rg**
- To disable the service: **accessibility disable -a AccessibilityExtAbility -b com.example.demo**
In the preceding commands, **AccessibilityExtAbility** indicates the name of the accessibility extension service, **com.example.demo** indicates the bundle name, and **rg** indicates the capabilities (**r** is short for retrieve).
If the service is enabled or disabled successfully, the message "enable ability successfully" or "disable ability successfully" is displayed.
...@@ -3,7 +3,8 @@ ...@@ -3,7 +3,8 @@
When developing an application, you may need to configure certain tags to identify the application, such as the bundle name and application icon. This topic describes key tags that need to be configured during application development. Icons and labels are usually configured together. There is the application icon, application label, entry icon, and entry label, which correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). The application icon and label are used in **Settings**. For example, they are displayed in the application list in **Settings**. The entry icon is displayed on the device's home screen after the application is installed. The entry icon maps to a [UIAbility](uiability-overview.md) component. Therefore, an application can have multiple entry icons and labels. When you touch one of them, the corresponding UIAbility page is displayed. When developing an application, you may need to configure certain tags to identify the application, such as the bundle name and application icon. This topic describes key tags that need to be configured during application development. Icons and labels are usually configured together. There is the application icon, application label, entry icon, and entry label, which correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). The application icon and label are used in **Settings**. For example, they are displayed in the application list in **Settings**. The entry icon is displayed on the device's home screen after the application is installed. The entry icon maps to a [UIAbility](uiability-overview.md) component. Therefore, an application can have multiple entry icons and labels. When you touch one of them, the corresponding UIAbility page is displayed.
**Figure 1** Icons and labels
**Figure 1** Icons and labels
![application-component-configuration-stage](figures/application-component-configuration-stage.png) ![application-component-configuration-stage](figures/application-component-configuration-stage.png)
...@@ -14,11 +15,11 @@ When developing an application, you may need to configure certain tags to identi ...@@ -14,11 +15,11 @@ When developing an application, you may need to configure certain tags to identi
- **Configuring the application icon and label** - **Configuring the application icon and label**
The application icon is specified by the **icon** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. The **icon** field must be set to the index of an image so that the image is displayed as the application icon. The application icon is usually displayed in an application list, for example, the application list in **Settings**. You must configure an icon and label for an application on the stage model.
The application label is specified by the **label** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** module of the project. The **label** field specifies the application name displayed to users. It must be set to the index of a string resource. The application icon is specified by the **icon** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. The **icon** field must be set to the index of an image so that the image is displayed as the application icon.
The **icon** and **label** fields in the **app.json5** file are under **app**, as follows: The application label is specified by the **label** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** module of the project. The **label** field specifies the application name displayed to users. It must be set to the index of a string resource.
```json ```json
{ {
...@@ -32,7 +33,9 @@ When developing an application, you may need to configure certain tags to identi ...@@ -32,7 +33,9 @@ When developing an application, you may need to configure certain tags to identi
- **Configuring the entry icon and label** - **Configuring the entry icon and label**
The entry icon and label are configured by specifying **icon** and **label** under **abilities** in the [module.json5 file](../quick-start/module-configuration-file.md). For example, if you want to display the icon and label of the UIAbility component on the home screen, add **entity.system.home** to **entities** and **action.system.home** to **actions** under **skills**. If the preceding fields are configured for multiple UIAbility components of an application, multiple icons and labels are displayed on the home screen, corresponding to their respective UIAbility component. On the stage model, you can configure an entry icon and label for each application component. The entry icon and label are displayed on the home screen.
The entry icon is configured by specifying **icon** under **abilities** in the [module.json5 file](../quick-start/module-configuration-file.md). For example, if you want to display the icon of the UIAbility component on the home screen, add **entity.system.home** to **entities** and **ohos.want.action.home** to **actions** under **skills**. If this field is configured for multiple UIAbility components of an application, multiple icons are displayed on the home screen, corresponding to their respective UIAbility component.
```json ```json
{ {
...@@ -49,7 +52,7 @@ When developing an application, you may need to configure certain tags to identi ...@@ -49,7 +52,7 @@ When developing an application, you may need to configure certain tags to identi
"entity.system.home" "entity.system.home"
], ],
"actions": [ "actions": [
"action.system.home" "ohos.want.action.home"
] ]
} }
], ],
...@@ -69,4 +72,3 @@ When developing an application, you may need to configure certain tags to identi ...@@ -69,4 +72,3 @@ When developing an application, you may need to configure certain tags to identi
- **Configuring the module permission** - **Configuring the module permission**
The **requestPermission** field in the [module.json5 file](../quick-start/module-configuration-file.md) is used to configure the permission information required by the module to access the protected part of the system or other applications. This field declares the name of the permission to request, the reason for requesting the permission, and the scenario where the permission is used. The **requestPermission** field in the [module.json5 file](../quick-start/module-configuration-file.md) is used to configure the permission information required by the module to access the protected part of the system or other applications. This field declares the name of the permission to request, the reason for requesting the permission, and the scenario where the permission is used.
...@@ -14,7 +14,7 @@ The stage model is designed based on the following considerations, which make it ...@@ -14,7 +14,7 @@ The stage model is designed based on the following considerations, which make it
1. **Designed for complex applications** 1. **Designed for complex applications**
- In the stage model, multiple application components share an ArkTS engine (VM running the programming language ArkTS) instance, making it easy for application components to share objects and status while requiring less memory. - In the stage model, multiple application components share an ArkTS engine (VM running the programming language ArkTS) instance, making it easy for application components to share objects and status while requiring less memory.
- The object-oriented development mode makes the code of complex applications easy to read, maintain, and scale. - The object-oriented development mode makes the code of complex applications easy to read, maintain, and scale.
2. **Native support for [cross-device migration](hop-cross-device-migration.md) and [multi-device collaboration](hop-multi-device-collaboration.md) at the application component level** 2. **Native support for [cross-device migration](hop-cross-device-migration.md) and [multi-device collaboration](hop-multi-device-collaboration.md) at the application component level**
...@@ -48,13 +48,12 @@ In the stage model, multiple application components share the same ArkTS engine ...@@ -48,13 +48,12 @@ In the stage model, multiple application components share the same ArkTS engine
The table below describes their differences in detail. The table below describes their differences in detail.
**Table 1** Differences between the FA model and stage model **Table 1** Differences between the FA model and stage model
| Item| FA model| Stage model| | Item| FA model| Stage model|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| **Application component**| 1. Component classification<br>- PageAbility: has the UI and supports user interaction. For details, see [PageAbility Component Overview](pageability-overview.md).<br>- ServiceAbility: provides background services and has no UI. For details, see [ServiceAbility Component Overview](serviceability-overview.md).<br>- DataAbility: provides the data sharing capability and has no UI. For details, see [DataAbility Component Overview](dataability-overview.md).<br>2. Development mode<br>Application components are specified by exporting anonymous objects and fixed entry files. You cannot perform derivation. It is inconvenient for capability expansion.| 1. Component classification<br>- UIAbility: has the UI and supports user interaction. For details, see [UIAbility Component Overview](uiability-overview.md).<br>- ExtensionAbility: provides extension capabilities (such as widget and input methods) for specific scenarios. For details, see [ExtensionAbility Component Overview](extensionability-overview.md).<br>2. Development mode<br>The object-oriented mode is used to provide open application components as classes. You can derive application components for capability expansion.| | **Application component**| 1. Component classification<br>![fa-model-component](figures/fa-model-component.png)<br/>- PageAbility: has the UI and supports user interaction For details, see [PageAbility Component Overview](pageability-overview.md).<br>- ServiceAbility: provides background services and has no UI. For details, see [ServiceAbility Component Overview](serviceability-overview.md).<br>- DataAbility: provides the data sharing capability and has no UI. For details, see [DataAbility Component Overview](dataability-overview.md).<br>2. Development mode<br>Application components are specified by exporting anonymous objects and fixed entry files. You cannot perform derivation. It is inconvenient for capability expansion. | 1. Component classification<br>![stage-model-component](figures/stage-model-component.png)<br/> - UIAbility: has the UI and supports user interaction. For details, see [UIAbility Component Overview](uiability-overview.md).<br>- ExtensionAbility: provides extension capabilities (such as widget and input methods) for specific scenarios. For details, see [ExtensionAbility Component Overview](extensionability-overview.md).<br>2. Development mode<br>The object-oriented mode is used to provide open application components as classes. You can derive application components for capability expansion. |
| **Process model**| There are two types of processes:<br>1. Main process<br>2. Rendering process<br>For details, see [Process Model (FA Model)](process-model-fa.md). | There are three types of processes:<br>1. Main process<br>2. ExtensionAbility process<br>3. Rendering process<br>For details, see [Process Model (Stage Model)](process-model-stage.md). | | **Process model**| There are two types of processes:<br>1. Main process<br>2. Rendering process<br>For details, see [Process Model (FA Model)](process-model-fa.md).| There are three types of processes:<br>1. Main process<br>2. ExtensionAbility process<br>3. Rendering process<br>For details, see [Process Model (Stage Model)](process-model-stage.md).|
| **Thread model**| 1. ArkTS engine instance creation<br>A process can run multiple application component instances, and each application component instance runs in an independent ArkTS engine instance.<br>2. Thread model<br>Each ArkTS engine instance is created on an independent thread (non-main thread). The main thread does not have an ArkTS engine instance.<br>3. Intra-process object sharing: not supported.<br>For details, see [Thread Model (FA Model)](thread-model-fa.md). | 1. ArkTS engine instance creation<br>A process can run multiple application component instances, and all application component instances share one ArkTS engine instance.<br>2. Thread model<br>The ArkTS engine instance is created on the main thread.<br>3. Intra-process object sharing: supported.<br>For details, see [Thread Model (Stage Model)](thread-model-stage.md). | | **Thread model**| 1. ArkTS engine instance creation<br>A process can run multiple application component instances, and each application component instance runs in an independent ArkTS engine instance.<br>2. Thread model<br>Each ArkTS engine instance is created on an independent thread (non-main thread). The main thread does not have an ArkTS engine instance.<br>3. Intra-process object sharing: not supported.<br>For details, see [Thread Model (FA Model)](thread-model-fa.md).| 1. ArkTS engine instance creation<br>A process can run multiple application component instances, and all application component instances share one ArkTS engine instance.<br>2. Thread model<br>The ArkTS engine instance is created on the main thread.<br>3. Intra-process object sharing: supported.<br>For details, see [Thread Model (Stage Model)](thread-model-stage.md).|
| **Mission management model**| - A mission is created for each PageAbility component instance.<br>- Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions.<br>- PageAbility components do not form a stack structure.<br>For details, see [Mission Management Scenarios](mission-management-overview.md).| - A mission is created for each UIAbility component instance.<br>- Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions.<br>- UIAbility components do not form a stack structure.<br>For details, see [Mission Management Scenarios](mission-management-overview.md).| | **Mission management model**| - A mission is created for each PageAbility component instance.<br>- Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions.<br>- PageAbility components do not form a stack structure.<br>For details, see [Mission Management Scenarios](mission-management-overview.md).| - A mission is created for each UIAbility component instance.<br>- Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions.<br>- UIAbility components do not form a stack structure.<br>For details, see [Mission Management Scenarios](mission-management-overview.md).|
| **Application configuration file**| The **config.json** file is used to describe the application, HAP, and application component information.<br>For details, see [Application Configuration File Overview (FA Model)](../quick-start/application-configuration-file-overview-fa.md).| The **app.json5** file is used to describe the application information, and the **module.json5** file is used to describe the HAP and application component information.<br>For details, see [Application Configuration File Overview (Stage Model)](../quick-start/application-configuration-file-overview-stage.md).| | **Application configuration file**| The **config.json** file is used to describe the application, HAP, and application component information.<br>For details, see [Application Configuration File Overview (FA Model)](../quick-start/application-configuration-file-overview-fa.md).| The **app.json5** file is used to describe the application information, and the **module.json5** file is used to describe the HAP and application component information.<br>For details, see [Application Configuration File Overview (Stage Model)](../quick-start/application-configuration-file-overview-stage.md).|
# DataShareExtensionAbility # DataShareExtensionAbility (System Applications Only)
DataShareExtensionAbility is available only for system application. It provides the data sharing capability. System applications can implement a DataShareExtensionAbility or access an existing DataShareExtensionAbility in the system. Third-party applications can only access an existing DataShareExtensionAbility. For details, see [DataShare Development](../database/database-datashare-guidelines.md). DataShareExtensionAbility provides the data sharing capability. System applications can implement a DataShareExtensionAbility or access an existing DataShareExtensionAbility in the system. Third-party applications can only access an existing DataShareExtensionAbility. For details, see [DataShare Development](../database/database-datashare-guidelines.md).
# EnterpriseAdminExtensionAbility Development
## Introduction
**EnterpriseAdminExtensionAbility** is essential to a mobile device management (MDM) application. When developing an MDM application for an enterprise, you must inherit the **EnterpriseAdminExtensionAbility** class and have the MDM service logic implemented in an **EnterpriseAdminExtensionAbility** instance. The **EnterpriseAdminExtensionAbility** class provides callbacks for the enable, disable, install, and uninstall events of a device administrator application, implementing notification of system administrator status changes.
## Constraints
- ***Function constraints***
The APIs provided can be used only by device administrator applications.
## Scenarios: Listening for the Enable, Disable, Install, and Uninstall Events of a Device Administrator Application
### Overview
**onAdminEnabled**: called when the enterprise administrator or employee deploys an MDM application and enables the DeviceAdmin permission for the application. The MDM application can set the initialization policy in the **onAdminEnabled** callback.
**onAdminDisabled**: called when the system or employee disables the DeviceAdmin permission to notify the enterprise administrator that the device is no longer managed.
**onBundleAdded**: called to notify the enterprise administrator that the specified MDM application is installed on the device. In enterprise application administration settings, after the enterprise administrator subscribes to application installation and uninstallation events, the MDM application reports the events through the callbacks.
**onBundleRemoved**: called to notify the enterprise administrator that the specified MDM application is uninstalled on the device.
### Available APIs
| Class | API | Description |
| :------------------------------ | ----------------------------------------- | ---------------------------- |
| EnterpriseAdminExtensionAbility | onAdminDisabled(): void | Called when the device administrator application is enabled.|
| EnterpriseAdminExtensionAbility | onBundleAdded(bundleName: string): void | Called when the MDM application is installed. |
| EnterpriseAdminExtensionAbility | onAdminEnabled(): void | Called when the device administrator application is disabled. |
| EnterpriseAdminExtensionAbility | onBundleRemoved(bundleName: string): void | Called when the MDM application is uninstalled. |
### How to Develop
To implement **EnterpriseAdminExtensionAbility**, enable the device administrator application and create an **ExtensionAbility** instance from the code directory of the device administrator application. The procedure is as follows:
1. In the **ets** directory of the target module, right-click and choose **New > Directory** to create a directory named **EnterpriseExtAbility**.
2. Right-click the **EnterpriseExtAbility** directory and choose **New > TypeScript File** to create a file named **EnterpriseExtAbility.ts**.
3. Open the **EnterpriseExtAbility.ts** file and import the **EnterpriseAdminExtensionAbility** module. Customize a class that inherits from **EnterpriseAdminExtensionAbility** and add the required callbacks, such as **onAdminEnabled()** and **onAdminDisabled()**, through which the enterprise administrator can receive notification when the device administrator application is enabled or disabled.
```ts
import EnterpriseAdminExtensionAbility from '@ohos.enterprise.EnterpriseAdminExtensionAbility';
export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility {
onAdminEnabled() {
console.info("onAdminEnabled");
}
onAdminDisabled() {
console.info("onAdminDisabled");
}
onBundleAdded(bundleName: string) {
console.info("EnterpriseAdminAbility onBundleAdded bundleName:" + bundleName)
}
onBundleRemoved(bundleName: string) {
console.info("EnterpriseAdminAbility onBundleRemoved bundleName" + bundleName)
}
};
```
4. Register **ServiceExtensionAbility** in the [module.json5](../quick-start/module-configuration-file.md) file of the target module. Among the parameters, set **type** to **enterpriseAdmin** and **srcEntrance** to the code path of the current ExtensionAbility.
```ts
"extensionAbilities": [
{
"name": "ohos.samples.enterprise_admin_ext_ability",
"type": "enterpriseAdmin",
"visible": true,
"srcEntrance": "./ets/enterpriseextability/EnterpriseAdminAbility.ts"
}
]
```
## Example
Use the **subscribeManagedEvent** and **unsubscribeManagedEvent** APIs in the **@ohos.enterprise.adminManager** module to subscribe to and unsubscribe from the application installation and uninstallation event, respectively. After the subscription is successful, the MDM application notifies the enterprise administrator when it is installed or uninstalled on the device.
```ts
@State managedEvents: Array<adminManager.ManagedEvent> = [0,1]
@State subscribeManagedEventMsg: string = ""
@State unsubscribeManagedEventMsg: string = ""
async subscribeManagedEventCallback() {
await adminManager.subscribeManagedEvent(this.admin,
[adminManager.ManagedEvent.MANAGED_EVENT_BUNDLE_ADDED,
adminManager.ManagedEvent.MANAGED_EVENT_BUNDLE_REMOVED], (error) => {
if (error) {
this.subscribeManagedEventMsg = 'subscribeManagedEvent Callback::errorCode: ' + error.code + ' errorMessage: ' + error.message
} else {
this.subscribeManagedEventMsg = 'subscribeManagedEvent Callback::success'
}
})
}
async unsubscribeManagedEventPromise() {
await adminManager.unsubscribeManagedEvent(this.admin,
[adminManager.ManagedEvent.MANAGED_EVENT_BUNDLE_ADDED,
adminManager.ManagedEvent.MANAGED_EVENT_BUNDLE_REMOVED]).then(() => {
this.unsubscribeManagedEventMsg = 'unsubscribeManagedEvent Promise::success'
}).catch((error) => {
this.unsubscribeManagedEventMsg = 'unsubscribeManagedEvent Promise::errorCode: ' + error.code + ' errorMessage: ' + error.message
})
}
```
...@@ -9,7 +9,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab ...@@ -9,7 +9,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab
- [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md): ExtensionAbility component of the form type, which provides APIs related to widgets. - [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md): ExtensionAbility component of the form type, which provides APIs related to widgets.
- [WorkSchedulerExtensionAbility](../reference/apis/js-apis-resourceschedule-workScheduler.md): ExtensionAbility component of the work_scheduler type, which provides callbacks for Work Scheduler tasks. - [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md): ExtensionAbility component of the work_scheduler type, which provides callbacks for Work Scheduler tasks.
- [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which provides an input method framework that can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more. - [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which provides an input method framework that can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more.
...@@ -21,7 +21,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab ...@@ -21,7 +21,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab
- [StaticSubscriberExtensionAbility](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md): ExtensionAbility component of the static_subscriber type, which provides APIs for static broadcast. - [StaticSubscriberExtensionAbility](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md): ExtensionAbility component of the static_subscriber type, which provides APIs for static broadcast.
- [WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md): ExtensionAbility component of the window type, which allows system applications to display UIs of other applications. - [WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md): ExtensionAbility component of the window type, which allows a system application to be embedded in and displayed over another application.
- [EnterpriseAdminExtensionAbility](../reference/apis/js-apis-EnterpriseAdminExtensionAbility.md): ExtensionAbility component of the enterprise_admin type, which provides APIs for processing enterprise management events, such as application installation events on devices and events indicating too many incorrect screen-lock password attempts. - [EnterpriseAdminExtensionAbility](../reference/apis/js-apis-EnterpriseAdminExtensionAbility.md): ExtensionAbility component of the enterprise_admin type, which provides APIs for processing enterprise management events, such as application installation events on devices and events indicating too many incorrect screen-lock password attempts.
......
# Cross-Device Migration # Cross-Device Migration (System Applications Only)]
## When to Use ## When to Use
Cross-device migration is available only for system applications. The main task is to migrate the current task (including the page control status) of an application to the target device so that the task can continue on it. Cross-device migration supports the following functionalities: The main task of cross-device migration is to migrate the current task (including the page control status) of an application to the target device so that the task can continue on it. Cross-device migration supports the following functionalities:
- Storage and restoration of custom data - Storage and restoration of custom data
......
# Multi-device Collaboration # Multi-device Collaboration (System Applications Only)
## When to Use ## When to Use
Multi-device coordination is available only for system applications. It involves the following scenarios: Multi-device coordination involves the following scenarios:
- [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned) - [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned)
...@@ -305,7 +305,7 @@ A system application can connect to a service on another device by calling [conn ...@@ -305,7 +305,7 @@ A system application can connect to a service on another device by calling [conn
## Using Cross-Device Ability Call ## Using Cross-Device Ability Call
The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction). The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction (System Applications Only)](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction-system-applications-only).
The following describes how to implement multi-device collaboration through cross-device ability call. The following describes how to implement multi-device collaboration through cross-device ability call.
......
...@@ -18,9 +18,9 @@ Each type of ExtensionAbility has its own context. ServiceExtensionAbility has [ ...@@ -18,9 +18,9 @@ Each type of ExtensionAbility has its own context. ServiceExtensionAbility has [
This topic describes how to use ServiceExtensionAbility in the following scenarios: This topic describes how to use ServiceExtensionAbility in the following scenarios:
- [Implementing a Background Service](#implementing-a-background-service) - [Implementing a Background Service (System Applications Only)](#implementing-a-background-service-system-applications-only)
- [Starting a Background Service](#starting-a-background-service) - [Starting a Background Service (System Applications Only)](#starting-a-background-service-system-applications-only)
- [Connecting to a Background Service](#connecting-to-a-background-service) - [Connecting to a Background Service](#connecting-to-a-background-service)
...@@ -33,9 +33,9 @@ This topic describes how to use ServiceExtensionAbility in the following scenari ...@@ -33,9 +33,9 @@ This topic describes how to use ServiceExtensionAbility in the following scenari
> - Third-party applications can connect to ServiceExtensionAbility provided by the system only when they gain focus in the foreground. > - Third-party applications can connect to ServiceExtensionAbility provided by the system only when they gain focus in the foreground.
## Implementing a Background Service ## Implementing a Background Service (System Applications Only)
This feature applies only to system applications. [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) provides the callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestory()**. Override them as required. The following figure shows the lifecycle of ServiceExtensionAbility. [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) provides the callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestory()**. Override them as required. The following figure shows the lifecycle of ServiceExtensionAbility.
**Figure 1** ServiceExtensionAbility lifecycle **Figure 1** ServiceExtensionAbility lifecycle
![ServiceExtensionAbility-lifecycle](figures/ServiceExtensionAbility-lifecycle.png) ![ServiceExtensionAbility-lifecycle](figures/ServiceExtensionAbility-lifecycle.png)
...@@ -164,9 +164,9 @@ To implement a background service, manually create a ServiceExtensionAbility com ...@@ -164,9 +164,9 @@ To implement a background service, manually create a ServiceExtensionAbility com
``` ```
## Starting a Background Service ## Starting a Background Service (System Applications Only)
This feature applies only to system applications. A system application uses the [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability) method to start a background service. The [onRequest()](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonrequest) callback is invoked, and the **Want** object passed by the caller is received through the callback. After the background service is started, its lifecycle is independent of that of the client. In other words, even if the client is destroyed, the background service can still run. Therefore, the background service must be stopped by calling [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) when its work is complete. Alternatively, another component can call [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) to stop the background service. A system application uses the [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability) method to start a background service. The [onRequest()](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonrequest) callback is invoked, and the **Want** object passed by the caller is received through the callback. After the background service is started, its lifecycle is independent of that of the client. In other words, even if the client is destroyed, the background service can still run. Therefore, the background service must be stopped by calling [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) when its work is complete. Alternatively, another component can call [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) to stop the background service.
> **NOTE** > **NOTE**
> >
......
# Starting a Remote PageAbility # Starting a Remote PageAbility (System Applications Only)
This feature applies only to system applications. The **startAbility()** method in the **featureAbility** class is used to start a remote PageAbility. The **startAbility()** method in the **featureAbility** class is used to start a remote PageAbility.
In addition to **'\@ohos.ability.featureAbility'**, you must import **'\@ohos.distributedHardware.deviceManager'**, which provides account-independent distributed device networking capabilities. Then you can use **getTrustedDeviceListSync** of the **DeviceManager** module to obtain the remote device ID and pass the remote device ID in the **want** parameter for starting the remote PageAbility. In addition to **'\@ohos.ability.featureAbility'**, you must import **'\@ohos.distributedHardware.deviceManager'**, which provides account-independent distributed device networking capabilities. Then you can use **getTrustedDeviceListSync** of the **DeviceManager** module to obtain the remote device ID and pass the remote device ID in the **want** parameter for starting the remote PageAbility.
......
# StaticSubscriberExtensionAbility Development
## Scenario Description
​The common event service provides two subscription modes: dynamic and static. In dynamic subscription mode, a subscriber calls an API during the running period to subscribe to common events. For details, see [Subscribing to Common Events](common-event-subscription.md). In static subscription mode, no common event subscription API is called. A common event is subscribed by configuring a declaration file and implementing a class that inherits from **StaticSubscriberExtensionAbility**. A static subscriber is started once it receives a target event (for example, a power-on event) published by the system or application. At the same time, the **onReceiveEvent** callback is triggered, in which you can implement the service logic. **The static subscriber APIs are system APIs and can be used only by system applications that have passed the system-level power consumption review.**
## How to Develop
1. Prerequisites
The application must meet the following requirements:
The application is a system application.
The application is developed using the full SDK.
The application's power consumption has passed the system-level power consumption review. If you want to use static subscription in the debugging phase, add the bundle name of your application to the system configuration file **/etc/static_subscriber_config.json**.
2. Declaring a Static Subscriber
To declare a static subscriber, create an ExtensionAbility, which is derived from the **StaticSubscriberExtensionAbility** class, in the project. The sample code is as follows:
```ts
import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility'
export default class StaticSubscriber extends StaticSubscriberExtensionAbility {
onReceiveEvent(event) {
console.log('onReceiveEvent, event:' + event.event);
}
}
```
You can implement service logic in the **onReceiveEvent** callback.
3. Project Configuration for a Static Subscriber
After writing the static subscriber code, configure the subscriber in the **module.json5** file. The configuration format is as follows:
```ts
{
"module": {
......
"extensionAbilities": [
{
"name": "StaticSubscriber",
"srcEntrance": "./ets/StaticSubscriber/StaticSubscriber.ts",
"description": "$string:StaticSubscriber_desc",
"icon": "$media:icon",
"label": "$string:StaticSubscriber_label",
"type": "staticSubscriber",
"visible": true,
"metadata": [
{
"name": "ohos.extension.staticSubscriber",
"resource": "$profile:subscribe"
}
]
}
]
......
}
}
```
Pay attention to the following fields in the JSON file:
**srcEntrance**: entry file path of the ExtensionAbility, that is, the file path of the static subscriber declared in Step 2.
**type**: ExtensionAbility type. For a static subscriber, set this field to **staticSubscriber**.
**metadata**: level-2 configuration file information of the ExtensionAbility. The configuration information varies according to the ExtensionAbility type. Therefore, you must use different config files to indicate the specific configuration. The **metadata** field contains two keywords: **name** and **resource**. The **name** field indicates the ExtensionAbility type name. For a static subscriber, declare the name as **ohos.extension.staticSubscriber** for successful identification. The **resource** field indicates the path that stores the ExtensionAbility configuration, which is customizable. In this example, the path is **resources/base/profile/subscribe.json**.
A level-2 configuration file pointed to by **metadata** must be in the following format:
```ts
{
"commonEvents": [
{
"name": "xxx",
"permission": "xxx",
"events":[
"xxx"
]
}
]
}
```
If the level-2 configuration file is not declared in this format, the file cannot be identified. The fields are described as follows:
**name**: name of the ExtensionAbility, which must be the same as the name of **extensionAbility** declared in **module.json5**.
**permission**: permission required by the publisher. If a publisher without the required permission attempts to publish an event, the event is regarded as invalid and will not be published.
**events**: list of subscribed target events
## Samples
For details about how to develop StaticSubscriberExtensionAbility, see [StaticSubscriber (ArkTS, API version 9, Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StaticSubscriber).
...@@ -17,7 +17,7 @@ This topic describes the UIAbility interaction modes in the following scenarios. ...@@ -17,7 +17,7 @@ This topic describes the UIAbility interaction modes in the following scenarios.
- [Starting a Specified Page of UIAbility](#starting-a-specified-page-of-uiability) - [Starting a Specified Page of UIAbility](#starting-a-specified-page-of-uiability)
- [Using Ability Call to Implement UIAbility Interaction](#using-ability-call-to-implement-uiability-interaction) - [Using Ability Call to Implement UIAbility Interaction (System Applications Only)](#using-ability-call-to-implement-uiability-interaction-system-applications-only)
## Starting UIAbility in the Same Application ## Starting UIAbility in the Same Application
...@@ -422,9 +422,9 @@ In summary, when a UIAbility instance of application A has been created and the ...@@ -422,9 +422,9 @@ In summary, when a UIAbility instance of application A has been created and the
> When the [launch type of the callee UIAbility](uiability-launch-type.md) is set to **standard**, a new instance is created each time the callee UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked. > When the [launch type of the callee UIAbility](uiability-launch-type.md) is set to **standard**, a new instance is created each time the callee UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked.
## Using Ability Call to Implement UIAbility Interaction ## Using Ability Call to Implement UIAbility Interaction (System Applications Only)
This feature applies only to system applications. Ability call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility 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 UIAbility instances (caller ability and callee ability) through IPC. Ability call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility 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 UIAbility instances (caller ability and callee ability) through 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:
......
...@@ -3,9 +3,11 @@ ...@@ -3,9 +3,11 @@
## Overview ## Overview
UIAbility has the UI and is mainly used for user interaction. UIAbility is a type of application component that provides the UI for user interaction.
UIAbility is the basic unit scheduled by the system and provides a window for applications to draw UIs. A UIAbility component can implement a functional module through multiple pages. Each UIAbility component instance corresponds to a mission in **Recents**. UIAbility is the basic unit scheduled by the system and provides a window for applications to draw UIs. An application can contain one or more UIAbility components. For example, for a payment application, you can use two UIAbility components to carry the entry and payment functionalities. You are advised to use one UIAbility component to carry the same functional module, with multiple pages (if necessary).
Each UIAbility component instance is displayed as a mission in Recents.
## Privacy Statement Configuration ## Privacy Statement Configuration
...@@ -32,8 +34,3 @@ To enable an application to properly use a UIAbility component, declare the UIAb ...@@ -32,8 +34,3 @@ To enable an application to properly use a UIAbility component, declare the UIAb
} }
} }
``` ```
> **NOTE**
>
> For the ability composition, see [Adding an Ability to a Module](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-ability-0000001218280664-V3).
...@@ -100,7 +100,7 @@ The widget provider development based on the [stage model](stage-model-developme ...@@ -100,7 +100,7 @@ The widget provider development based on the [stage model](stage-model-developme
- [Configuring the Widget Configuration File](#configuring-the-widget-configuration-file): Configure the application configuration file **module.json5** and profile configuration file. - [Configuring the Widget Configuration File](#configuring-the-widget-configuration-file): Configure the application configuration file **module.json5** and profile configuration file.
- [Persistently Storing Widget Data](#persistently-storing-widget-data): Perform persistent management on widget information. - [Persistently Storing Widget Data](#persistently-storing-widget-data): This operation is a form of widget data exchange.
- [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed on a widget. - [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed on a widget.
...@@ -597,3 +597,13 @@ The following is an example: ...@@ -597,3 +597,13 @@ The following is an example:
}; };
``` ```
## Restrictions
To minimize the abuse of **FormExtensionAbility** by third-party applications, the following APIs cannot be invoked in **FormExtensionAbility**:
- @ohos.ability.particleAbility.d.ts
- @ohos.backgroundTaskManager.d.ts
- @ohos.resourceschedule.backgroundTaskManager.d.ts
- @ohos.multimedia.camera.d.ts
- @ohos.multimedia.audio.d.ts
- @ohos.multimedia.media.d.ts
# WindowExtensionAbility
[WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md) is a type of ExtensionAbility component that allows a system application to be embedded in and displayed over another application.
The WindowExtensionAbility component must be used together with the [AbilityComponent](../reference/arkui-ts/ts-container-ability-component.md) to process services of the started application. WindowExtensionAbility is run in connection mode. A system application must use the AbilityComponent to start the WindowExtensionAbility component.
Each ExtensionAbility has its own context. For WindowExtensionAbility,
the context is [WindowExtensionContext](../reference/apis/js-apis-inner-application-windowExtensionContext.md).
> **NOTE**
>
> **WindowExtensionAbility** is a system API. To embed a third-party application in another application and display it over the application, switch to the full SDK by following the instructions provided in [Guide to Switching to Full SDK](../../application-dev/quick-start/full-sdk-switch-guide.md).
>
## Setting an Embedded Ability (System Applications Only)
The **WindowExtensionAbility** class provides **onConnect()**, **onDisconnect()**, and **onWindowReady()** lifecycle callbacks, which can be overridden.
- The **onWindowReady()** callback is invoked when a window is created for the ability.
- The **onConnect()** callback is invoked when the AbilityComponent corresponding to the window connects to the ability.
- The **onDisconnect()** callback is invoked when the AbilityComponent disconnects from the ability.
**How to Develop**
To implement an embedded application, manually create a WindowExtensionAbility in DevEco Studio as follows:
1. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **WindowExtAbility**.
2. Right-click the **WindowExtAbility** directory, and choose **New > TypeScript File** to create a file named **WindowExtAbility.ts**.
3. Open the **WindowExtAbility.ts** file and import the dependency package of **WindowExtensionAbility**. Customize a class that inherits from **WindowExtensionAbility** and implement the **onWindowReady()**, **onConnect()**, and **onDisconnect()** lifecycle callbacks.
```ts
import Extension from '@ohos.application.WindowExtensionAbility'
export default class WindowExtAbility extends Extension {
onWindowReady(window) {
window.loadContent('WindowExtAbility/pages/index1').then(() => {
window.getProperties().then((pro) => {
console.log("WindowExtension " + JSON.stringify(pro));
})
window.show();
})
}
onConnect(want) {
console.info('JSWindowExtension onConnect ' + want.abilityName);
}
onDisconnect(want) {
console.info('JSWindowExtension onDisconnect ' + want.abilityName);
}
}
```
4. Register the WindowExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the **Module** project. Set **type** to **"window"** and **srcEntrance** to the code path of the ExtensionAbility component.
```json
{
"module": {
"extensionAbilities": [
{
"name": "WindowExtAbility",
"srcEntrance": "./ets/WindowExtAbility/WindowExtAbility.ts",
"icon": "$media:icon",
"description": "WindowExtension",
"type": "window",
"visible": true,
}
],
}
}
```
## Starting an Embedded Ability (System Applications Only)
System applications can load the created WindowExtensionAbility through the AbilityComponent.
**How to Develop**
1. To connect to an embedded application, add the AbilityComponent to the corresponding pages in the DevEco Studio project.
2. Set **bundleName** and **abilityName** in the AbilityComponent.
3. Set the width and height. The sample code is as follows:
```ts
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
AbilityComponent({ abilityName: "WindowExtAbility", bundleName: "com.example.WindowExtAbility"})
.width(500)
.height(500)
}
.width('100%')
}
.height('100%')
.backgroundColor(0x64BB5c)
}
}
```
...@@ -19,7 +19,7 @@ Call **createDistributedObject()** to create a distributed data object instance. ...@@ -19,7 +19,7 @@ Call **createDistributedObject()** to create a distributed data object instance.
| Bundle Name| API| Description| | Bundle Name| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>- **source**: attributes of the distributed data object to set.<br>- **DistributedObject**: returns the distributed data object created. | | ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>- **source**: attributes of the distributed data object to create.<br>- **DistributedObject**: returns the distributed data object created.|
### Generating a Session ID ### Generating a Session ID
...@@ -91,10 +91,9 @@ The following example shows how to implement distributed data object synchroniza ...@@ -91,10 +91,9 @@ The following example shows how to implement distributed data object synchroniza
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
``` ```
2. Apply for the permission. 2. Apply for the permission.
Add the permissions required (FA model) to the **config.json** file. Add the required permission (FA model) to the **config.json** file.
```json ```json
{ {
...@@ -112,18 +111,43 @@ The following example shows how to implement distributed data object synchroniza ...@@ -112,18 +111,43 @@ The following example shows how to implement distributed data object synchroniza
This permission must also be granted by the user when the application is started for the first time. This permission must also be granted by the user when the application is started for the first time.
```js ```js
// FA model
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
function grantPermission() { function grantPermission() {
console.info('grantPermission'); console.info('grantPermission');
let context = featureAbility.getContext(); let context = featureAbility.getContext();
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
console.info(`result.requestCode=${result.requestCode}`) console.info(`requestPermissionsFromUser CallBack`);
}) })
console.info('end grantPermission'); console.info('end grantPermission');
} }
grantPermission();
```
```ts
// Stage model
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
context = this.context;
}
}
function grantPermission() {
let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC'];
context.requestPermissionsFromUser(permissions).then((data) => {
console.info('success: ${data}');
}).catch((error) => {
console.error('failed: ${error}');
});
}
grantPermission(); grantPermission();
``` ```
...@@ -139,10 +163,10 @@ The following example shows how to implement distributed data object synchroniza ...@@ -139,10 +163,10 @@ The following example shows how to implement distributed data object synchroniza
}); });
let sessionId = distributedObject.genSessionId(); let sessionId = distributedObject.genSessionId();
``` ```
4. Add the distributed data object instance to a network for data synchronization. The data objects in the synchronization network include the local and remote objects. 4. Add the distributed data object instance to a network for data synchronization. The data objects in the synchronization network include the local and remote objects.
```js ```js
// Local object // Local object
let localObject = distributedObject.createDistributedObject({ let localObject = distributedObject.createDistributedObject({
name: "jack", name: "jack",
...@@ -164,7 +188,7 @@ The following example shows how to implement distributed data object synchroniza ...@@ -164,7 +188,7 @@ The following example shows how to implement distributed data object synchroniza
// After learning that the local device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18. // After learning that the local device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18.
remoteObject.setSessionId(sessionId); remoteObject.setSessionId(sessionId);
``` ```
5. Observe the data changes of the distributed data object. You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be invoked to return the data changes. 5. Observe the data changes of the distributed data object. You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be invoked to return the data changes.
```js ```js
...@@ -202,33 +226,29 @@ The following example shows how to implement distributed data object synchroniza ...@@ -202,33 +226,29 @@ The following example shows how to implement distributed data object synchroniza
localObject.parent.mother = "mom"; localObject.parent.mother = "mom";
``` ```
7. Access the distributed data object. 7. Access the distributed data object.<br>Obtain the distributed data object attributes, which are the latest data on the network.
Obtain the distributed data object attributes, which are the latest data on the network.
```js ```js
console.info("name " + localObject["name"]); console.info("name " + localObject["name"]);
``` ```
8. Unsubscribe from data changes. You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered. 8. Unsubscribe from data changes. You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered.
```js ```js
// Unregister the specified data change callback. // Unregister the specified data change callback.
localObject.off("change", changeCallback); localObject.off("change", changeCallback);
// Unregister all data change callbacks. // Unregister all data change callbacks.
localObject.off("change"); localObject.off("change");
``` ```
9. Subscribe to status changes of this distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. 9. Subscribe to status changes of this distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline.
```js ```js
function statusCallback(sessionId, networkId, status) { function statusCallback(sessionId, networkId, status) {
this.response += "status changed " + sessionId + " " + status + " " + networkId; this.response += "status changed " + sessionId + " " + status + " " + networkId;
} }
localObject.on("status", this.statusCallback); localObject.on("status", this.statusCallback);
``` ```
10. Save a distributed data object and delete it. 10. Save a distributed data object and delete it.
```js ```js
...@@ -247,20 +267,16 @@ console.info("name " + localObject["name"]); ...@@ -247,20 +267,16 @@ console.info("name " + localObject["name"]);
console.info("revokeSave failed."); console.info("revokeSave failed.");
}); });
``` ```
11. Unsubscribe from the status changes of this distributed data object. You can specify the callback to unregister. If you do not specify the callback, this API unregisters all status change callbacks of this distributed data object.
11. Unsubscribe from the status changes of the distributed data object.
You can specify the callback to unregister. If you do not specify the callback, all status change callbacks of this distributed data object will be unregistered.
```js ```js
// Unregister the specified status change callback. // Unregister the specified status change callback.
localObject.off("status", this.statusCallback); localObject.off("status", this.statusCallback);
// Unregister all status change callbacks. // Unregister all status change callbacks.
localObject.off("status"); localObject.off("status");
``` ```
12. Remove the distributed data object from the synchronization network. The data changes on the local object will not be synchronized to the removed distributed data object. 12. Remove the distributed data object from the synchronization network. The data changes on the local object will not be synchronized to the removed distributed data object.
```js ```js
localObject.setSessionId(""); localObject.setSessionId("");
``` ```
...@@ -13,7 +13,7 @@ For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis ...@@ -13,7 +13,7 @@ For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis
| 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): KVManager | Creates a **KvManager** object for database management. |
| getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Creates and obtains a KV store.| | getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;T extends KVStore&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. |
...@@ -117,16 +117,10 @@ The following uses a single KV store as an example to describe the development p ...@@ -117,16 +117,10 @@ The following uses a single KV store as an example to describe the development p
bundleName: 'com.example.datamanagertest', bundleName: 'com.example.datamanagertest',
context:context, context:context,
} }
distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) { kvManager = distributedKVStore.createKVManager(kvManagerConfig);
if (err) { console.log("Created KVManager successfully");
console.error(`Failed to create KVManager. code is ${err.code},message is ${err.message}`);
return;
}
console.log('Created KVManager successfully');
kvManager = manager;
});
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`Failed to create KVManager. Code is ${e.code}, message is ${e.message}`);
} }
``` ```
...@@ -150,14 +144,14 @@ The following uses a single KV store as an example to describe the development p ...@@ -150,14 +144,14 @@ The following uses a single KV store as an example to describe the development p
}; };
kvManager.getKVStore('storeId', options, function (err, store) { kvManager.getKVStore('storeId', options, function (err, store) {
if (err) { if (err) {
console.error(`Failed to get KVStore: code is ${err.code},message is ${err.message}`); console.error(`Failed to get KVStore: code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.log('Obtained KVStore successfully'); console.log('Obtained KVStore successfully');
kvStore = store; kvStore = store;
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred. Code is ${e.code}, message is ${e.message}`);
} }
``` ```
...@@ -175,7 +169,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -175,7 +169,7 @@ The following uses a single KV store as an example to describe the development p
console.log(`dataChange callback call data: ${data}`); console.log(`dataChange callback call data: ${data}`);
}); });
}catch(e){ }catch(e){
console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occured. Code is ${e.code}, message is ${e.message}`);
} }
``` ```
...@@ -192,13 +186,13 @@ The following uses a single KV store as an example to describe the development p ...@@ -192,13 +186,13 @@ The following uses a single KV store as an example to describe the development p
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.error(`Failed to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put data. 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.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred. Code is ${e.code}, message is ${e.message}`);
} }
``` ```
...@@ -215,20 +209,20 @@ The following uses a single KV store as an example to describe the development p ...@@ -215,20 +209,20 @@ The following uses a single KV store as an example to describe the development p
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.error(`Failed to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put data. 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) {
if (err != undefined) { if (err != undefined) {
console.error(`Failed to get data.code is ${err.code},message is ${err.message}`); console.error(`Failed to obtain data. Code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.log(`Obtained data successfully:${data}`); console.log(`Obtained data successfully:${data}`);
}); });
}); });
}catch (e) { }catch (e) {
console.error(`Failed to get.code is ${e.code},message is ${e.message}`); console.error(`Failed to obtain data. Code is ${e.code}, message is ${e.message}`);
} }
``` ```
...@@ -262,7 +256,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -262,7 +256,7 @@ The following uses a single KV store as an example to describe the development p
// 1000 indicates that the maximum delay is 1000 ms. // 1000 indicates that the maximum delay is 1000 ms.
kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000); kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000);
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred. code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred. Code is ${e.code}, message is ${e.message}`);
} }
} }
}); });
......
...@@ -114,21 +114,19 @@ You can use the following APIs to delete a **Preferences** instance or data file ...@@ -114,21 +114,19 @@ You can use the following APIs to delete a **Preferences** instance or data file
```ts ```ts
// Obtain the context. // Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
let preferences = null; let preferences = null;
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage) {
context = this.context; let promise = data_preferences.getPreferences(this.context, 'mystore');
promise.then((pref) => {
preferences = pref;
}).catch((err) => {
console.info("Failed to get the preferences.");
})
} }
} }
let promise = data_preferences.getPreferences(context, 'mystore');
promise.then((pref) => {
preferences = pref;
}).catch((err) => {
console.info("Failed to get the preferences.");
})
``` ```
3. Write data. 3. Write data.
......
...@@ -39,8 +39,8 @@ When an asynchronous callback is used, the return value can be processed directl ...@@ -39,8 +39,8 @@ When an asynchronous callback is used, the return value can be processed directl
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import errorManager from '@ohos.app.ability.errorManager'; import errorManager from '@ohos.app.ability.errorManager';
var registerId = -1; let registerId = -1;
var callback = { let callback = {
onUnhandledException: function (errMsg) { onUnhandledException: function (errMsg) {
console.log(errMsg); console.log(errMsg);
} }
...@@ -48,13 +48,13 @@ var callback = { ...@@ -48,13 +48,13 @@ var callback = {
export default class EntryAbility extends Ability { export default class EntryAbility extends Ability {
onCreate(want, launchParam) { onCreate(want, launchParam) {
console.log("[Demo] EntryAbility onCreate") console.log("[Demo] EntryAbility onCreate")
registerId = errorManager.registerErrorObserver(callback); registerId = errorManager.on("error", callback);
globalThis.abilityWant = want; globalThis.abilityWant = want;
} }
onDestroy() { onDestroy() {
console.log("[Demo] EntryAbility onDestroy") console.log("[Demo] EntryAbility onDestroy")
errorManager.unregisterErrorObserver(registerId, (result) => { errorManager.off("error", registerId, (result) => {
console.log("[Demo] result " + result.code + ";" + result.message) console.log("[Demo] result " + result.code + ";" + result.message)
}); });
} }
......
...@@ -9,11 +9,10 @@ FilePicker provides the following modes: ...@@ -9,11 +9,10 @@ FilePicker provides the following modes:
## Development Guidelines ## Development Guidelines
> **NOTE** > **NOTE**
>
> FilePicker supports only the applications developed based on the stage model. > FilePicker supports only the applications developed based on the stage model.
> For details about the stage model, see [Interpretation of the Application Model](../application-models/application-model-description.md). > For details about the stage model, see [Interpretation of the Application Model](../application-models/application-model-description.md).
You can use [AbilityContext.startAbilityForResult(want, options)](../reference/apis/js-apis-ability-context.md##abilitycontextstartabilityforresult-1) with different parameters to start different FilePicker modes. You can use [AbilityContext.startAbilityForResult(want, options)](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilityforresult-1) with different parameters to start FilePicker in different modes.
You need to use [Want](../reference/apis/js-apis-application-want.md) to specify **bundleName** and **abilityName** to start FilePicker. For details, see the following sample code. You need to use [Want](../reference/apis/js-apis-application-want.md) to specify **bundleName** and **abilityName** to start FilePicker. For details, see the following sample code.
...@@ -32,8 +31,7 @@ ArkTS sample code: ...@@ -32,8 +31,7 @@ ArkTS sample code:
// Start FilePicker to select a file. // Start FilePicker to select a file.
globalThis.context.startAbilityForResult( globalThis.context.startAbilityForResult(
{ {
bundleName: "com.ohos.filepicker", action: "ohos.want.action.OPEN_FILE",
abilityName: "MainAbility",
parameters: { parameters: {
'startMode': 'choose', //choose or save 'startMode': 'choose', //choose or save
} }
...@@ -44,8 +42,7 @@ globalThis.context.startAbilityForResult( ...@@ -44,8 +42,7 @@ globalThis.context.startAbilityForResult(
// Start FilePicker to save a file. // Start FilePicker to save a file.
globalThis.context.startAbilityForResult( globalThis.context.startAbilityForResult(
{ {
bundleName: "com.ohos.filepicker", action: "ohos.want.action.CREATE_FILE",
abilityName: "MainAbility",
parameters: { parameters: {
'startMode': 'save', //choose or save 'startMode': 'save', //choose or save
'saveFile': 'test.jpg', 'saveFile': 'test.jpg',
......
...@@ -39,19 +39,19 @@ The following describes how to create an album named **myAlbum**. ...@@ -39,19 +39,19 @@ The following describes how to create an album named **myAlbum**.
```ts ```ts
async function example() { async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE; let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_IMAGE); const path = await media.getPublicDirectory(DIR_IMAGE);
// myAlbum is the path for storing the new file and the name of the new album. // myAlbum is the path for storing the new file and the name of the new album.
media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => { media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => {
if (fileAsset != undefined) { if (fileAsset === undefined) {
console.info('createAlbum successfully, message = ' + fileAsset); console.error('createAlbum failed, message = ' + err);
} else { } else {
console.info('createAlbum failed, message = ' + err); console.info('createAlbum successfully, message = ' + JSON.stringify(fileAsset));
} }
}); });
} }
``` ```
...@@ -75,20 +75,20 @@ The following describes how to rename the album **newAlbum**. ...@@ -75,20 +75,20 @@ The following describes how to rename the album **newAlbum**.
```ts ```ts
async function example() { async function example() {
let AlbumNoArgsfetchOp = { let AlbumNoArgsfetchOp = {
selections: '', selections: '',
selectionArgs: [], selectionArgs: [],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let albumList = await media.getAlbums(AlbumNoArgsfetchOp); let albumList = await media.getAlbums(AlbumNoArgsfetchOp);
let album = albumList[0]; let album = albumList[0];
album.albumName = 'newAlbum'; album.albumName = 'newAlbum';
// Void callback. // Void callback.
album.commitModify().then(function() { album.commitModify().then(() => {
console.info("albumRename successfully"); console.info("albumRename successfully");
}).catch(function(err){ }).catch((err) => {
console.info("albumRename failed with error: " + err); console.error("albumRename failed with error: " + err);
}); });
} }
``` ```
...@@ -37,15 +37,15 @@ The following describes how to obtain the public directory that stores camera fi ...@@ -37,15 +37,15 @@ The following describes how to obtain the public directory that stores camera fi
```ts ```ts
async function example(){ async function example(){
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
const dicResult = await media.getPublicDirectory(DIR_CAMERA); const dicResult = await media.getPublicDirectory(DIR_CAMERA);
if (dicResult == 'Camera/') { if (dicResult == 'Camera/') {
console.info('mediaLibraryTest : getPublicDirectory passed'); console.info('mediaLibraryTest : getPublicDirectory passed');
} else { } else {
console.info('mediaLibraryTest : getPublicDirectory failed'); console.error('mediaLibraryTest : getPublicDirectory failed');
} }
} }
``` ```
...@@ -59,47 +59,52 @@ Users can access files stored in the public directories through the system appli ...@@ -59,47 +59,52 @@ Users can access files stored in the public directories through the system appli
You can call [mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1) to open a file in a public directory. You can call [mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1) to open a file in a public directory.
You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to open a file in the application sandbox. The sandbox directory can be accessed only through the application context. You can call [fs.open](../reference/apis/js-apis-file-fs.md#fsopen) to open a file in the application sandbox. The sandbox directory can be accessed only through the application context.
**Prerequisites** **Prerequisites**
- 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 permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA**.
- You have imported the module [@ohos.fileio](../reference/apis/js-apis-fileio.md) in addition to @ohos.multimedia.mediaLibrary. - You have imported the module [@ohos.file.fs](../reference/apis/js-apis-file-fs.md) in addition to @ohos.multimedia.mediaLibrary.
- The **testFile.txt** file has been created and contains content.
**How to Develop** **How to Develop**
1. Call [context.filesDir](../reference/apis/js-apis-inner-app-context.md#contextgetfilesdir) to obtain the directory of the application sandbox. 1. Call [context.filesDir](../reference/apis/js-apis-file-fs.md) to obtain the directory of the application sandbox.
2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory. 2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory.
3. Call **fileio.open** to open the file in the sandbox. 3. Call **fs.open** to open the file in the sandbox.
4. Call **fileAsset.open** to open the file in the public directory. 4. Call **fileAsset.open** to open the file in the public directory.
5. Call **fileio.copyfile** to copy the file. 5. Call [fs.copyfile](../reference/apis/js-apis-file-fs.md#fscopyfile) to copy the file.
6. Call **fileAsset.close** and **fileio.close** to close the file. 6. Call **fileAsset.close** and [fs.close](../reference/apis/js-apis-file-fs.md#fsclose) to close the file.
**Example 1: Copying Files from the Public Directory to the Sandbox** **Example 1: Copying Files from the Public Directory to the Sandbox**
```ts ```ts
async function copyPublic2Sandbox() { async function copyPublic2Sandbox() {
try {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = globalThis.context.filesDir; let sandboxDirPath = context.filesDir;
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?', selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile.txt'], selectionArgs: ['testFile.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject(); let fileAsset = await fetchResult.getFirstObject();
let fdPub = await fileAsset.open('rw'); let fdPub = await fileAsset.open('rw');
let fdSand = await fileio.open(sandboxDirPath + '/testFile.txt', 0o2 | 0o100, 0o666); let fdSand = await fs.open(sandboxDirPath + '/testFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
await fileio.copyFile(fdPub, fdSand); await fs.copyFile(fdPub, fdSand.fd);
await fileAsset.close(fdPub); await fileAsset.close(fdPub);
await fileio.close(fdSand); await fs.close(fdSand.fd);
let content_sand = await fileio.readText(sandboxDirPath + '/testFile.txt'); let content_sand = await fs.readText(sandboxDirPath + '/testFile.txt');
console.log('content read from sandbox file: ', content_sand) console.info('content read from sandbox file: ', content_sand)
} catch (err) {
console.info('[demo] copyPublic2Sandbox fail, err: ', err);
}
} }
``` ```
...@@ -107,81 +112,81 @@ async function copyPublic2Sandbox() { ...@@ -107,81 +112,81 @@ async function copyPublic2Sandbox() {
```ts ```ts
async function copySandbox2Public() { async function copySandbox2Public() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = globalThis.context.filesDir; let sandboxDirPath = context.filesDir;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS); const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS);
try { try {
let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath); let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath);
console.info('createFile successfully, message = ' + fileAsset); console.info('createFile successfully, message = ' + fileAsset);
} catch (err) { } catch (err) {
console.info('createFile failed, message = ' + err); console.error('createFile failed, message = ' + err);
} }
try { try {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?', selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile02.txt'], selectionArgs: ['testFile02.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
var fileAsset = await fetchResult.getFirstObject(); var fileAsset = await fetchResult.getFirstObject();
} catch (err) { } catch (err) {
console.info('file asset get failed, message = ' + err); console.error('file asset get failed, message = ' + err);
} }
let fdPub = await fileAsset.open('rw'); let fdPub = await fileAsset.open('rw');
let fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2); let fdSand = await fs.open(sandboxDirPath + 'testFile.txt', OpenMode.READ_WRITE);
await fileio.copyFile(fdSand, fdPub); await fs.copyFile(fdSand.fd, fdPub);
await fileio.close(fdPub); await fileAsset.close(fdPub);
await fileio.close(fdSand); await fs.close(fdSand.fd);
let fdPubRead = await fileAsset.open('rw'); let fdPubRead = await fileAsset.open('rw');
try { try {
let arrayBuffer = new ArrayBuffer(4096); let arrayBuffer = new ArrayBuffer(4096);
await fileio.read(fdPubRead, arrayBuffer); await fs.read(fdPubRead, arrayBuffer);
var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer)); var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer));
fileAsset.close(fdPubRead); fileAsset.close(fdPubRead);
} catch (err) { } catch (err) {
console.log('read text failed, message = ', err); console.error('read text failed, message = ', err);
} }
console.log('content read from public file: ', content_pub); console.info('content read from public file: ', content_pub);
} }
``` ```
### Reading and Writing a File ### Reading and Writing a File
You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../reference/apis/js-apis-medialibrary.md) to open and close a file, and use **fileio.read** and **fileio.write** of [fileio](../reference/apis/js-apis-fileio.md) to read and write a file. You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../reference/apis/js-apis-medialibrary.md) to open and close a file, and use **fs.read** and **fs.write** in [file.fs](../reference/apis/js-apis-file-fs.md) to read and write the file.
**Prerequisites** **Prerequisites**
- 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 permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA**.
- You have imported the module [@ohos.fileio](../reference/apis/js-apis-fileio.md) in addition to @ohos.multimedia.mediaLibrary. - You have imported the module [@ohos.file.fs](../reference/apis/js-apis-file-fs.md) in addition to @ohos.multimedia.mediaLibrary.
**How to Develop** **How to Develop**
1. Create a file. 1. Create a file.
```ts ```ts
async function example() { async function example() {
let mediaType = mediaLibrary.MediaType.FILE; let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS); const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then (function (asset) { media.createAsset(mediaType, "testFile.text", path).then((asset) => {
console.info("createAsset successfully:" + JSON.stringify(asset)); console.info("createAsset successfully:" + JSON.stringify(asset));
}).catch(function(err){ }).catch((err) => {
console.info("createAsset failed with error: " + err); console.error("createAsset failed with error: " + err);
}); });
} }
``` ```
2. Call **FileAsset.open** to open the file. 2. Call **FileAsset.open** to open the file.
3. Call **fileio.write** to write a string to the file. 3. Call [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to write a string to the file.
4. Call **fileio.read** to read the file and save the data read in an array buffer. 4. Call [fs.read](../reference/apis/js-apis-file-fs.md#fsread) to read the file and save the data read in an array buffer.
5. Convert the array buffer to a string. 5. Convert the array buffer to a string.
...@@ -191,25 +196,25 @@ You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../refe ...@@ -191,25 +196,25 @@ You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../refe
```ts ```ts
async function writeOnlyPromise() { async function writeOnlyPromise() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?', selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile.txt'], selectionArgs: ['testFile.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject(); let fileAsset = await fetchResult.getFirstObject();
console.info('fileAssetName: ', fileAsset.displayName); console.info('fileAssetName: ', fileAsset.displayName);
try { try {
let fd = await fileAsset.open('w'); let fd = await fileAsset.open('w');
console.info('file descriptor: ', fd); console.info('file descriptor: ', fd);
await fileio.write(fd, "Write file test content."); await fs.write(fd, "Write file test content.");
await fileAsset.close(fd); await fileAsset.close(fd);
} catch (err) { } catch (err) {
console.info('write file failed, message = ', err); console.error('write file failed, message = ', err);
} }
} }
``` ```
...@@ -217,28 +222,28 @@ async function writeOnlyPromise() { ...@@ -217,28 +222,28 @@ async function writeOnlyPromise() {
```ts ```ts
async function readOnlyPromise() { async function readOnlyPromise() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' , selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selectionArgs: ['testFile.txt'], selectionArgs: ['testFile.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject(); let fileAsset = await fetchResult.getFirstObject();
console.info('fileAssetName: ', fileAsset.displayName); console.info('fileAssetName: ', fileAsset.displayName);
try { try {
let fd = await fileAsset.open('r'); let fd = await fileAsset.open('r');
let arrayBuffer = new ArrayBuffer(4096); let arrayBuffer = new ArrayBuffer(4096);
await fileio.read(fd, arrayBuffer); await fs.read(fd, arrayBuffer);
let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer)); let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer));
globalThis.fileContent = fileContent; globalThis.fileContent = fileContent;
globalThis.fileName = fileAsset.displayName; globalThis.fileName = fileAsset.displayName;
console.info('file content: ', fileContent); console.info('file content: ', fileContent);
await fileAsset.close(fd); await fileAsset.close(fd);
} catch (err) { } catch (err) {
console.info('read file failed, message = ', err); console.error('read file failed, message = ', err);
} }
} }
``` ```
...@@ -64,64 +64,64 @@ After configuring the permissions in the **module.json5** file, the application ...@@ -64,64 +64,64 @@ After configuring the permissions in the **module.json5** file, the application
1. Declare the permissions in the **module.json5** file. Add the **requestPermissions** tag under **module** in the file, and set the tag based on the project requirements. For details about the tag, see [Guide for Requesting Permissions from User](../security/accesstoken-guidelines.md). 1. Declare the permissions in the **module.json5** file. Add the **requestPermissions** tag under **module** in the file, and set the tag based on the project requirements. For details about the tag, see [Guide for Requesting Permissions from User](../security/accesstoken-guidelines.md).
```json ```json
{ {
"module": { "module": {
"requestPermissions": [ "requestPermissions": [
{ {
"name": "ohos.permission.MEDIA_LOCATION", "name": "ohos.permission.MEDIA_LOCATION",
"reason": "$string:reason", "reason": "$string:reason",
"usedScene": { "usedScene": {
"abilities": [ "abilities": [
"EntryAbility" "EntryAbility"
], ],
"when": "always" "when": "always"
} }
}, },
{ {
"name": "ohos.permission.READ_MEDIA", "name": "ohos.permission.READ_MEDIA",
"reason": "$string:reason", "reason": "$string:reason",
"usedScene": { "usedScene": {
"abilities": [ "abilities": [
"EntryAbility" "EntryAbility"
], ],
"when": "always" "when": "always"
} }
}, },
{ {
"name": "ohos.permission.WRITE_MEDIA", "name": "ohos.permission.WRITE_MEDIA",
"reason": "$string:reason", "reason": "$string:reason",
"usedScene": { "usedScene": {
"abilities": [ "abilities": [
"EntryAbility" "EntryAbility"
], ],
"when": "always" "when": "always"
} }
} }
] ]
} }
} }
``` ```
2. In the **Ability.ts** file, call **requestPermissionsFromUser** in the **onWindowStageCreate** callback to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box. 2. In the **Ability.ts** file, call **requestPermissionsFromUser** in the **onWindowStageCreate** callback to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
let list : Array<Permissions> = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA']; let list : Array<Permissions> = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA'];
let permissionRequestResult; let permissionRequestResult;
let atManager = abilityAccessCtrl.createAtManager(); let atManager = abilityAccessCtrl.createAtManager();
atManager.requestPermissionsFromUser(this.context, list, (err, result) => { atManager.requestPermissionsFromUser(this.context, list, (err, result) => {
if (err) { if (err) {
console.log('requestPermissionsFromUserError: ' + JSON.stringify(err)); console.error('requestPermissionsFromUserError: ' + JSON.stringify(err));
} else { } else {
permissionRequestResult=result; permissionRequestResult = result;
console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); console.info('permissionRequestResult: ' + JSON.stringify(permissionRequestResult));
} }
}); });
} }
} }
``` ```
...@@ -33,30 +33,33 @@ To specify the image as the media type, set **selectionArgs** to **MediaType.IMA ...@@ -33,30 +33,33 @@ To specify the image as the media type, set **selectionArgs** to **MediaType.IMA
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE; let fileType = mediaLibrary.MediaType.IMAGE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getFirstObject().then((fileAsset) => {
fetchFileResult.getNextObject((err, fileAsset) => { console.log('getFirstObject.displayName : ' + fileAsset.displayName);
if (err) { for (let i = 1; i < fetchFileResult.getCount(); i++) {
console.error('Failed '); fetchFileResult.getNextObject().then((fileAsset) => {
return; console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
} }).catch((err) => {
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.error('Failed to get next object: ' + err);
}) });
} }
}).catch((err) => {
console.error('Failed to get first object: ' + err);
});
} }
``` ```
### Querying Media Assets with the Specified Date ### Querying Media Assets with the Specified Date
The following describes how to obtain media assets that are added on the specified date. You can also use the modification date and shooting date as the retrieval conditions. The following describes how to obtain all the media assets that are added from the specified date. You can also use the modification date and shooting date as the retrieval conditions.
To specify the date when the files are added as the retrieval condition, set **selections** to **FileKey.DATE_ADDED**. To specify the date when the files are added as the retrieval condition, set **selections** to **FileKey.DATE_ADDED**.
...@@ -64,23 +67,26 @@ To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**. ...@@ -64,23 +67,26 @@ To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**.
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let option = { let option = {
selections: fileKeyObj.DATE_ADDED + '= ?', selections: fileKeyObj.DATE_ADDED + '> ?',
selectionArgs: ['2022-8-5'], selectionArgs: ['2022-8-5'],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getFirstObject().then((fileAsset) => {
fetchFileResult.getNextObject((err, fileAsset) => { console.info('getFirstObject.displayName : ' + fileAsset.displayName);
if (err) { for (let i = 1; i < fetchFileResult.getCount(); i++) {
console.error('Failed '); fetchFileResult.getNextObject().then((fileAsset) => {
return; console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
} }).catch((err) => {
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.error('Failed to get next object: ' + err);
}) });
} }
}).catch((err) => {
console.error('Failed to get first object: ' + err);
});
} }
``` ```
...@@ -92,25 +98,28 @@ To sort files in descending order by the date when they are added, set **order** ...@@ -92,25 +98,28 @@ To sort files in descending order by the date when they are added, set **order**
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE; let fileType = mediaLibrary.MediaType.IMAGE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + " DESC",
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getFirstObject().then((fileAsset) => {
fetchFileResult.getNextObject((err, fileAsset) => { console.info('getFirstObject.displayName : ' + fileAsset.displayName);
if (err) { for (let i = 1; i < fetchFileResult.getCount(); i++) {
console.error('Failed '); fetchFileResult.getNextObject().then((fileAsset) => {
return; console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
} }).catch((err) => {
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.error('Failed to get next object: ' + err);
}) });
} }
}).catch((err) => {
console.error('Failed to get first object: ' + err);
});
} }
``` ```
...@@ -124,31 +133,29 @@ To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**. ...@@ -124,31 +133,29 @@ To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**.
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE; let option = {
let option = { selections: fileKeyObj.ALBUM_NAME + '= ?',
selections: fileKeyObj.ALBUM_NAME + '= ?', selectionArgs: ['myAlbum'],
selectionArgs: ['myAlbum'], };
}; const context = getContext(this);
const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option);
const fetchFileResult = await media.getFileAssets(option); if (albumList.length > 0) {
for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getFirstObject().then((album) => {
fetchFileResult.getNextObject((err, fileAsset) => { console.info('getFirstObject.displayName : ' + album.albumName);
if (err) { }).catch((err) => {
console.error('Failed '); console.error('Failed to get first object: ' + err);
return; });
} } else {
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.info('getAlbum list is: 0');
}) }
}
} }
``` ```
## Obtaining Images and Videos in an Album ## Obtaining Images and Videos in an Album
You can obtain media assets in an album in either of the following ways: You can obtain media assets in an album in either of the following ways:
- Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified, as described in [Querying Media Assets with the Specfied Album Name](#querying-media-assets-with-the-specified-album-name). - Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified, as described in [Querying Media Assets with the Specfied Album Name](#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. - 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.
...@@ -163,24 +170,24 @@ The following describes how to obtain videos in an album named **New Album 1**. ...@@ -163,24 +170,24 @@ The following describes how to obtain videos in an album named **New Album 1**.
1. Create a retrieval condition for obtaining the target **Album** instance. 1. Create a retrieval condition for obtaining the target **Album** instance.
```ts ```ts
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let AlbumNoArgsFetchOp = { let AlbumNoArgsFetchOp = {
selections: fileKeyObj.ALBUM_NAME + '= ?', selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs:['New Album 1'] selectionArgs:['New Album 1']
} }
``` ```
2. Create a retrieval condition for obtaining videos in the target album. 2. Create a retrieval condition for obtaining videos in the target album.
```ts ```ts
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.VIDEO; let videoType = mediaLibrary.MediaType.VIDEO;
let imagesFetchOp = { let videoFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [videoType.toString()],
} }
``` ```
3. Call **Album.getFileAssets** to obtain the videos in the target album. 3. Call **Album.getFileAssets** to obtain the videos in the target album.
...@@ -188,28 +195,28 @@ Complete sample code: ...@@ -188,28 +195,28 @@ Complete sample code:
```ts ```ts
async function getCameraImagePromise() { async function getCameraImagePromise() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let videoType = mediaLibrary.MediaType.VIDEO;
let imagesFetchOp = { let videoFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [videoType.toString()],
} }
let AlbumNoArgsFetchOp = { let AlbumNoArgsFetchOp = {
selections: fileKeyObj.ALBUM_NAME + '= ?', selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs:['New Album 1'] selectionArgs:['New Album 1']
} }
let albumList = await media.getAlbums(AlbumNoArgsFetchOp); let albumList = await media.getAlbums(AlbumNoArgsFetchOp);
if (albumList.length > 0) { if (albumList.length > 0) {
const album = albumList[0]; const album = albumList[0];
let fetchFileResult = await album.getFileAssets(imagesFetchOp); let fetchFileResult = await album.getFileAssets(videoFetchOp);
let count = fetchFileResult.getCount(); let count = fetchFileResult.getCount();
console.info("get mediaLibrary IMAGE number", count); console.info("get mediaLibrary VIDEO number", count);
} else { } else {
console.info('getAlbum list is: 0'); console.info('getAlbum list is: 0');
} }
} }
``` ```
...@@ -235,31 +242,32 @@ The following describes how to obtain the thumbnail (size: 720 x 720) of the fir ...@@ -235,31 +242,32 @@ The following describes how to obtain the thumbnail (size: 720 x 720) of the fir
```ts ```ts
async function getFirstThumbnailPromise() { async function getFirstThumbnailPromise() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let imagesFetchOp = { let imagesFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
} }
let size = { width: 720, height: 720 }; let size = { width: 720, height: 720 };
const fetchFileResult = await media.getFileAssets(imagesFetchOp); const fetchFileResult = await media.getFileAssets(imagesFetchOp);
if (fetchFileResult != undefined) { if (fetchFileResult === undefined) {
const asset = await fetchFileResult.getFirstObject(); console.error("get image failed with error");
asset.getThumbnail(size).then((pixelMap) => { return;
pixelMap.getImageInfo().then((info) => { } else {
console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height); const asset = await fetchFileResult.getFirstObject();
}).catch((err) => { asset.getThumbnail(size).then((pixelMap) => {
console.info("getImageInfo failed with error:" + err); pixelMap.getImageInfo().then((info) => {
}); console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height);
}).catch((err) => { }).catch((err) => {
console.info("getImageInfo failed with error:" + err); console.error("getImageInfo failed with error: " + err);
}); });
} else { }).catch((err) => {
console.info("get image failed with error"); console.error("getImageInfo failed with error: " + err);
} });
}
} }
``` ```
...@@ -277,16 +285,16 @@ The following describes how to create a file of the **MediaType.FILE** type. ...@@ -277,16 +285,16 @@ The following describes how to create a file of the **MediaType.FILE** type.
```ts ```ts
async function example() { async function example() {
let mediaType = mediaLibrary.MediaType.FILE; let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS); const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then ((asset) => { media.createAsset(mediaType, "testFile.text", path).then((asset) => {
console.info("createAsset successfully:"+ JSON.stringify(asset)); console.info("createAsset successfully:"+ JSON.stringify(asset));
}).catch((err) => { }).catch((err) => {
console.info("createAsset failed with error:"+ err); console.error("createAsset failed with error: " + err);
}); });
} }
``` ```
...@@ -312,26 +320,26 @@ The following describes how to move the first file in the result set to the recy ...@@ -312,26 +320,26 @@ The following describes how to move the first file in the result set to the recy
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE; let fileType = mediaLibrary.MediaType.FILE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject(); let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) { if (asset === undefined) {
console.error('asset not exist'); console.error('asset not exist');
return; return;
} }
// Void callback. // Void callback.
asset.trash(true).then(() => { asset.trash(true).then(() => {
console.info("trash successfully"); console.info("trash successfully");
}).catch((err) => { }).catch((err) => {
console.info("trash failed with error: " + err); console.error("trash failed with error: " + err);
}); });
} }
``` ```
...@@ -346,7 +354,7 @@ Before renaming a file, you must obtain the file, for example, by calling [Fetch ...@@ -346,7 +354,7 @@ Before renaming a file, you must obtain the file, for example, by calling [Fetch
- 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**.
The following describes how to rename the first file in the result set as **newtitle.text**. The following describes how to rename the first file in the result set as **newImage.jpg**.
**How to Develop** **How to Develop**
...@@ -358,28 +366,28 @@ The following describes how to rename the first file in the result set as **newt ...@@ -358,28 +366,28 @@ The following describes how to rename the first file in the result set as **newt
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE; let fileType = mediaLibrary.MediaType.IMAGE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject(); let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) { if (asset === undefined) {
console.error('asset not exist'); console.error('asset not exist');
return;
}
asset.displayName = 'newImage.jpg';
// Void callback.
asset.commitModify((err) => {
if (err) {
console.error('fileRename Failed ');
return; return;
} }
asset.displayName = 'newImage.jpg'; console.info('fileRename successful.');
// Void callback. });
asset.commitModify((err) => {
if (err) {
console.error('fileRename Failed ');
return;
}
console.log('fileRename successful.');
});
} }
``` ```
# Media # Media
- Audio - Audio and Video
- [Audio Overview](audio-overview.md) - [Audio Overview](audio-overview.md)
- [Audio Playback Development](audio-playback.md)
- [Audio Recording Development](audio-recorder.md)
- [Audio Rendering Development](audio-renderer.md) - [Audio Rendering Development](audio-renderer.md)
- [Audio Stream Management Development](audio-stream-manager.md) - [Audio Stream Management Development](audio-stream-manager.md)
- [Audio Capture Development](audio-capturer.md) - [Audio Capture Development](audio-capturer.md)
...@@ -12,8 +10,10 @@ ...@@ -12,8 +10,10 @@
- [Audio Interruption Mode Development](audio-interruptmode.md) - [Audio Interruption Mode Development](audio-interruptmode.md)
- [Volume Management Development](audio-volume-manager.md) - [Volume Management Development](audio-volume-manager.md)
- [Audio Routing and Device Management Development](audio-routing-manager.md) - [Audio Routing and Device Management Development](audio-routing-manager.md)
- [AVPlayer Development (Recommended)](avplayer-playback.md)
- Video - [AVRecorder Development (Recommended)](avrecorder.md)
- [Audio Playback Development](audio-playback.md)
- [Audio Recording Development](audio-recorder.md)
- [Video Playback Development](video-playback.md) - [Video Playback Development](video-playback.md)
- [Video Recording Development](video-recorder.md) - [Video Recording Development](video-recorder.md)
......
...@@ -72,7 +72,7 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference ...@@ -72,7 +72,7 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
} }
await audioCapturer.start(); await audioCapturer.start();
let state = audioCapturer.state; state = audioCapturer.state;
if (state == audio.AudioState.STATE_RUNNING) { if (state == audio.AudioState.STATE_RUNNING) {
console.info('AudioRecLog: Capturer started'); console.info('AudioRecLog: Capturer started');
} else { } else {
...@@ -86,7 +86,7 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference ...@@ -86,7 +86,7 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
The following example shows how to write recorded data into a file. The following example shows how to write recorded data into a file.
```js ```js
import fileio from '@ohos.fileio'; import fs from '@ohos.file.fs';
let state = audioCapturer.state; let state = audioCapturer.state;
// The read operation can be performed only when the state is STATE_RUNNING. // The read operation can be performed only when the state is STATE_RUNNING.
...@@ -96,31 +96,36 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference ...@@ -96,31 +96,36 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
} }
const path = '/data/data/.pulse_dir/capture_js.wav'; // Path for storing the collected audio file. const path = '/data/data/.pulse_dir/capture_js.wav'; // Path for storing the collected audio file.
let fd = fileio.openSync(path, 0o102, 0o777); let file = fs.openSync(filePath, 0o2);
if (fd !== null) { let fd = file.fd;
console.info('AudioRecLog: file fd created'); if (file !== null) {
} console.info('AudioRecLog: file created');
else{ } else {
console.info('AudioRecLog: file fd create : FAILED'); console.info('AudioRecLog: file create : FAILED');
return; return;
} }
fd = fileio.openSync(path, 0o2002, 0o666);
if (fd !== null) { if (fd !== null) {
console.info('AudioRecLog: file fd opened in append mode'); console.info('AudioRecLog: file fd opened in append mode');
} }
let numBuffersToCapture = 150; // Write data for 150 times. let numBuffersToCapture = 150; // Write data for 150 times.
let count = 0;
while (numBuffersToCapture) { while (numBuffersToCapture) {
let bufferSize = await audioCapturer.getBufferSize();
let buffer = await audioCapturer.read(bufferSize, true); let buffer = await audioCapturer.read(bufferSize, true);
let options = {
offset: count * this.bufferSize,
length: this.bufferSize
}
if (typeof(buffer) == undefined) { if (typeof(buffer) == undefined) {
console.info('AudioRecLog: read buffer failed'); console.info('AudioRecLog: read buffer failed');
} else { } else {
let number = fileio.writeSync(fd, buffer); let number = fs.writeSync(fd, buffer, options);
console.info(`AudioRecLog: data written: ${number}`); console.info(`AudioRecLog: data written: ${number}`);
} }
numBuffersToCapture--; numBuffersToCapture--;
count++;
} }
``` ```
...@@ -189,7 +194,7 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference ...@@ -189,7 +194,7 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
let audioTime : number = await audioCapturer.getAudioTime(); let audioTime : number = await audioCapturer.getAudioTime();
// Obtain a proper minimum buffer size. // Obtain a proper minimum buffer size.
let bufferSize : number = await audioCapturer.getBuffersize(); let bufferSize : number = await audioCapturer.getBufferSize();
``` ```
7. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event. 7. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event.
......
...@@ -38,7 +38,7 @@ For details about the **src** types supported by **AudioPlayer**, see the [src a ...@@ -38,7 +38,7 @@ For details about the **src** types supported by **AudioPlayer**, see the [src a
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
// Print the stream track information. // Print the stream track information.
function printfDescription(obj) { function printfDescription(obj) {
...@@ -112,14 +112,8 @@ async function audioPlayerDemo() { ...@@ -112,14 +112,8 @@ async function audioPlayerDemo() {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path 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) => { let file = await fs.open(path);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
``` ```
...@@ -128,7 +122,7 @@ async function audioPlayerDemo() { ...@@ -128,7 +122,7 @@ async function audioPlayerDemo() {
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
export class AudioDemo { export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
...@@ -154,14 +148,8 @@ export class AudioDemo { ...@@ -154,14 +148,8 @@ export class AudioDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path 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) => { let file = await fs.open(path);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
} }
...@@ -171,7 +159,7 @@ export class AudioDemo { ...@@ -171,7 +159,7 @@ export class AudioDemo {
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
export class AudioDemo { export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
...@@ -202,14 +190,8 @@ export class AudioDemo { ...@@ -202,14 +190,8 @@ export class AudioDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path 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) => { let nextFile = await fs.open(nextpath);
nextFdPath = nextFdPath + '' + fdNumber; nextFdPath = nextFdPath + '' + nextFile.fd;
console.info('open fd success fd is' + nextFdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = nextFdPath; // Set the src attribute and trigger the 'dataLoad' event callback. audioPlayer.src = nextFdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
...@@ -220,14 +202,8 @@ export class AudioDemo { ...@@ -220,14 +202,8 @@ export class AudioDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path 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) => { let file = await fs.open(path);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
} }
...@@ -237,7 +213,7 @@ export class AudioDemo { ...@@ -237,7 +213,7 @@ export class AudioDemo {
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
export class AudioDemo { export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
...@@ -259,14 +235,8 @@ export class AudioDemo { ...@@ -259,14 +235,8 @@ export class AudioDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path 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) => { let file = await fs.open(path);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
} }
......
...@@ -33,31 +33,30 @@ The following figure shows the audio renderer state transitions. ...@@ -33,31 +33,30 @@ The following figure shows the audio renderer state transitions.
For details about the APIs, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). For details about the APIs, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8).
1. Use **createAudioRenderer()** to create an **AudioRenderer** instance. 1. Use **createAudioRenderer()** to create an **AudioRenderer** instance.
Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification. Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification.
```js ```js
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
let audioStreamInfo = { let audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1, channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
} }
let audioRendererInfo = { let audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH, content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0. rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0.
}
let audioRendererOptions = {
streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo
} }
let audioRendererOptions = {
streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo
}
let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); let audioRenderer = await audio.createAudioRenderer(audioRendererOptions);
console.log("Create audio renderer success."); console.log("Create audio renderer success.");
``` ```
2. Use **start()** to start audio rendering. 2. Use **start()** to start audio rendering.
...@@ -90,7 +89,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ...@@ -90,7 +89,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer. Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer.
```js ```js
import fileio from '@ohos.fileio'; import fs from '@ohos.file.fs';
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
async function writeBuffer(buf) { async function writeBuffer(buf) {
...@@ -109,35 +108,33 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ...@@ -109,35 +108,33 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
// Set a proper buffer size for the audio renderer. You can also select a buffer of another size. // Set a proper buffer size for the audio renderer. You can also select a buffer of another size.
const bufferSize = await audioRenderer.getBufferSize(); const bufferSize = await audioRenderer.getBufferSize();
let dir = globalThis.fileDir; // You must use the sandbox path. let dir = globalThis.fileDir; // You must use the sandbox path.
const path = dir + '/file_example_WAV_2MG.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/file_example_WAV_2MG.wav const filePath = dir + '/file_example_WAV_2MG.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/file_example_WAV_2MG.wav
console.info(`file path: ${ path}`); console.info(`file filePath: ${ filePath}`);
let ss = fileio.createStreamSync(path, 'r');
const totalSize = fileio.statSync(path).size; // Size of the file to render. let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
let discardHeader = new ArrayBuffer(bufferSize); let stat = await fs.stat(filePath); // Music file information.
ss.readSync(discardHeader); let buf = new ArrayBuffer(bufferSize);
let rlen = 0; let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1);
rlen += bufferSize; for (let i = 0;i < len; i++) {
let options = {
let id = setInterval(() => { offset: i * this.bufferSize,
if (audioRenderer.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state. length: this.bufferSize
ss.closeSync();
await audioRenderer.stop();
clearInterval(id);
}
if (audioRenderer.state == audio.AudioState.STATE_RUNNING) {
if (rlen >= totalSize) { // The rendering stops if the file finishes reading.
ss.closeSync();
await audioRenderer.stop();
clearInterval(id);
}
let buf = new ArrayBuffer(bufferSize);
rlen += ss.readSync(buf);
console.info(`Total bytes read from file: ${rlen}`);
writeBuffer(buf);
} else {
console.info('check after next interval');
} }
}, 30); // The timer interval is set based on the audio format. The unit is millisecond. let readsize = await fs.read(file.fd, buf, options)
let writeSize = await new Promise((resolve,reject)=>{
this.audioRenderer.write(buf,(err,writeSize)=>{
if(err){
reject(err)
}else{
resolve(writeSize)
}
})
})
}
fs.close(file)
await audioRenderer.stop(); // Stop rendering.
await audioRenderer.release(); // Releases the resources.
``` ```
4. (Optional) Call **pause()** or **stop()** to pause or stop rendering. 4. (Optional) Call **pause()** or **stop()** to pause or stop rendering.
...@@ -192,7 +189,6 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ...@@ -192,7 +189,6 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
} }
await audioRenderer.drain(); await audioRenderer.drain();
state = audioRenderer.state; state = audioRenderer.state;
} }
``` ```
...@@ -209,7 +205,6 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ...@@ -209,7 +205,6 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
console.info('Renderer already released'); console.info('Renderer already released');
return; return;
} }
await audioRenderer.release(); await audioRenderer.release();
state = audioRenderer.state; state = audioRenderer.state;
...@@ -242,7 +237,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ...@@ -242,7 +237,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
let audioTime : number = await audioRenderer.getAudioTime(); let audioTime : number = await audioRenderer.getAudioTime();
// Obtain a proper minimum buffer size. // Obtain a proper minimum buffer size.
let bufferSize : number = await audioRenderer.getBuffersize(); let bufferSize : number = await audioRenderer.getBufferSize();
// Obtain the audio renderer rate. // Obtain the audio renderer rate.
let renderRate : audio.AudioRendererRate = await audioRenderer.getRenderRate(); let renderRate : audio.AudioRendererRate = await audioRenderer.getRenderRate();
...@@ -424,35 +419,31 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ...@@ -424,35 +419,31 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
let dir = globalThis.fileDir; // You must use the sandbox path. let dir = globalThis.fileDir; // You must use the sandbox path.
const path1 = dir + '/music001_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music001_48000_32_1.wav const path1 = dir + '/music001_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music001_48000_32_1.wav
console.info(`audioRender1 file path: ${ path1}`); console.info(`audioRender1 file path: ${ path1}`);
let ss1 = await fileio.createStream(path1,'r'); let file1 = fs.openSync(path1, fs.OpenMode.READ_ONLY);
const totalSize1 = fileio.statSync(path1).size; // Size of the file to render. let stat = await fs.stat(path1); // Music file information.
console.info(`totalSize1 -------: ${totalSize1}`); let buf = new ArrayBuffer(bufferSize);
let discardHeader = new ArrayBuffer(bufferSize); let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1);
ss1.readSync(discardHeader);
let rlen = 0;
rlen += bufferSize;
// 1.7 Render the original audio data in the buffer by using audioRender. // 1.7 Render the original audio data in the buffer by using audioRender.
let id = setInterval(async () => { for (let i = 0;i < len; i++) {
if (audioRenderer1.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state. let options = {
ss1.closeSync(); offset: i * this.bufferSize,
audioRenderer1.stop(); length: this.bufferSize
clearInterval(id);
} }
if (audioRenderer1.state == audio.AudioState.STATE_RUNNING) { let readsize = await fs.read(file.fd, buf, options)
if (rlen >= totalSize1) { // The rendering stops if the file finishes reading. let writeSize = await new Promise((resolve,reject)=>{
ss1.closeSync(); this.audioRenderer1.write(buf,(err,writeSize)=>{
await audioRenderer1.stop(); if(err){
clearInterval(id); reject(err)
} }else{
let buf = new ArrayBuffer(bufferSize); resolve(writeSize)
rlen += ss1.readSync(buf); }
console.info(`Total bytes read from file: ${rlen}`); })
await writeBuffer(buf, that.audioRenderer1); })
} else { }
console.info('check after next interval'); fs.close(file1)
} await audioRenderer1.stop(); // Stop rendering.
}, 30); // The timer interval is set based on the audio format. The unit is millisecond. await audioRenderer1.release(); Releases the resources.
} }
async runningAudioRender2(){ async runningAudioRender2(){
...@@ -499,36 +490,32 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ...@@ -499,36 +490,32 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
// 2.6 Read the original audio data file. // 2.6 Read the original audio data file.
let dir = globalThis.fileDir; // You must use the sandbox path. let dir = globalThis.fileDir; // You must use the sandbox path.
const path2 = dir + '/music002_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music002_48000_32_1.wav const path2 = dir + '/music002_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music002_48000_32_1.wav
console.error(`audioRender1 file path: ${ path2}`); console.info(`audioRender2 file path: ${ path2}`);
let ss2 = await fileio.createStream(path2,'r'); let file2 = fs.openSync(path2, fs.OpenMode.READ_ONLY);
const totalSize2 = fileio.statSync(path2).size; // Size of the file to render. let stat = await fs.stat(path2); // Music file information.
console.error(`totalSize2 -------: ${totalSize2}`); let buf = new ArrayBuffer(bufferSize);
let discardHeader2 = new ArrayBuffer(bufferSize); let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1);
ss2.readSync(discardHeader2);
let rlen = 0;
rlen += bufferSize;
// 2.7 Render the original audio data in the buffer by using audioRender. // 2.7 Render the original audio data in the buffer by using audioRender.
let id = setInterval(async () => { for (let i = 0;i < len; i++) {
if (audioRenderer2.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state. let options = {
ss2.closeSync(); offset: i * this.bufferSize,
that.audioRenderer2.stop(); length: this.bufferSize
clearInterval(id);
}
if (audioRenderer1.state == audio.AudioState.STATE_RUNNING) {
if (rlen >= totalSize2) { // The rendering stops if the file finishes reading.
ss2.closeSync();
await audioRenderer2.stop();
clearInterval(id);
}
let buf = new ArrayBuffer(bufferSize);
rlen += ss2.readSync(buf);
console.info(`Total bytes read from file: ${rlen}`);
await writeBuffer(buf, that.audioRenderer2);
} else {
console.info('check after next interval');
} }
}, 30); // The timer interval is set based on the audio format. The unit is millisecond. let readsize = await fs.read(file.fd, buf, options)
let writeSize = await new Promise((resolve,reject)=>{
this.audioRenderer2.write(buf,(err,writeSize)=>{
if(err){
reject(err)
}else{
resolve(writeSize)
}
})
})
}
fs.close(file2)
await audioRenderer2.stop(); // Stop rendering.
await audioRenderer2.release(); // Releases the resources.
} }
async writeBuffer(buf, audioRender) { async writeBuffer(buf, audioRender) {
......
...@@ -104,7 +104,7 @@ The full playback process includes creating an instance, setting resources, sett ...@@ -104,7 +104,7 @@ The full playback process includes creating an instance, setting resources, sett
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
const TAG = 'AVPlayerDemo:' const TAG = 'AVPlayerDemo:'
export class AVPlayerDemo { export class AVPlayerDemo {
...@@ -223,14 +223,8 @@ export class AVPlayerDemo { ...@@ -223,14 +223,8 @@ export class AVPlayerDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path 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\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
let path = pathDir + '/H264_AAC.mp4' let path = pathDir + '/H264_AAC.mp4'
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path)
fdPath = fdPath + '' + fdNumber fdPath = fdPath + '' + file.fd
console.info('open fd success fd is' + fdPath)
}, (err) => {
console.info('open fd failed err is' + err)
}).catch((err) => {
console.info('open fd failed err is' + err)
});
this.avPlayer.url = fdPath this.avPlayer.url = fdPath
} }
} }
...@@ -240,7 +234,7 @@ export class AVPlayerDemo { ...@@ -240,7 +234,7 @@ export class AVPlayerDemo {
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
const TAG = 'AVPlayerDemo:' const TAG = 'AVPlayerDemo:'
export class AVPlayerDemo { export class AVPlayerDemo {
...@@ -280,7 +274,7 @@ export class AVPlayerDemo { ...@@ -280,7 +274,7 @@ export class AVPlayerDemo {
break; break;
case 'stopped': // This state is reported upon a successful callback of stop(). case 'stopped': // This state is reported upon a successful callback of stop().
console.info(TAG + 'state stopped called') console.info(TAG + 'state stopped called')
this.avPlayer.reset() // Call reset() to initialize the AVPlayer state. this.avPlayer.release() // Call reset() to initialize the AVPlayer state.
break; break;
case 'released': case 'released':
console.info(TAG + 'state released called') console.info(TAG + 'state released called')
...@@ -302,24 +296,18 @@ export class AVPlayerDemo { ...@@ -302,24 +296,18 @@ export class AVPlayerDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path 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\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
let path = pathDir + '/H264_AAC.mp4' let path = pathDir + '/H264_AAC.mp4'
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path)
fdPath = fdPath + '' + fdNumber fdPath = fdPath + '' + file.fd
console.info('open fd success fd is' + fdPath)
}, (err) => {
console.info('open fd failed err is' + err)
}).catch((err) => {
console.info('open fd failed err is' + err)
});
this.avPlayer.url = fdPath this.avPlayer.url = fdPath
} }
} }
``` ```
### Switching to the Next Video Clip ### Looping a Song
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
const TAG = 'AVPlayerDemo:' const TAG = 'AVPlayerDemo:'
export class AVPlayerDemo { export class AVPlayerDemo {
...@@ -362,7 +350,7 @@ export class AVPlayerDemo { ...@@ -362,7 +350,7 @@ export class AVPlayerDemo {
break; break;
case 'stopped': // This state is reported upon a successful callback of stop(). case 'stopped': // This state is reported upon a successful callback of stop().
console.info(TAG + 'state stopped called') console.info(TAG + 'state stopped called')
this.avPlayer.reset() // Call reset() to initialize the AVPlayer state. this.avPlayer.release() // Call reset() to initialize the AVPlayer state.
break; break;
case 'released': case 'released':
console.info(TAG + 'state released called') console.info(TAG + 'state released called')
...@@ -393,23 +381,17 @@ export class AVPlayerDemo { ...@@ -393,23 +381,17 @@ export class AVPlayerDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path 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\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
let path = pathDir + '/H264_AAC.mp4' let path = pathDir + '/H264_AAC.mp4'
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path)
fdPath = fdPath + '' + fdNumber fdPath = fdPath + '' + file.fd
console.info('open fd success fd is' + fdPath)
}, (err) => {
console.info('open fd failed err is' + err)
}).catch((err) => {
console.info('open fd failed err is' + err)
});
this.avPlayer.url = fdPath this.avPlayer.url = fdPath
} }
} }
``` ```
### Looping a Song ### Switching to the Next Video Clip
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
const TAG = 'AVPlayerDemo:' const TAG = 'AVPlayerDemo:'
export class AVPlayerDemo { export class AVPlayerDemo {
...@@ -422,14 +404,8 @@ export class AVPlayerDemo { ...@@ -422,14 +404,8 @@ export class AVPlayerDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path 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\H264_MP3.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_MP3.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
let path = pathDir + '/H264_MP3.mp4' let path = pathDir + '/H264_MP3.mp4'
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path)
fdPath = fdPath + '' + fdNumber fdPath = fdPath + '' + file.fd
console.info('open fd success fd is' + fdPath)
}, (err) => {
console.info('open fd failed err is' + err)
}).catch((err) => {
console.info('open fd failed err is' + err)
});
this.avPlayer.url = fdPath // The initialized state is reported again. this.avPlayer.url = fdPath // The initialized state is reported again.
} }
...@@ -493,14 +469,8 @@ export class AVPlayerDemo { ...@@ -493,14 +469,8 @@ export class AVPlayerDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path 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\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
let path = pathDir + '/H264_AAC.mp4' let path = pathDir + '/H264_AAC.mp4'
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path)
fdPath = fdPath + '' + fdNumber fdPath = fdPath + '' + file.fd
console.info('open fd success fd is' + fdPath)
}, (err) => {
console.info('open fd failed err is' + err)
}).catch((err) => {
console.info('open fd failed err is' + err)
});
this.avPlayer.url = fdPath this.avPlayer.url = fdPath
} }
} }
......
...@@ -69,14 +69,14 @@ export class AVRecorderDemo { ...@@ -69,14 +69,14 @@ export class AVRecorderDemo {
let surfaceID; // The surface ID is obtained by calling getInputSurface and transferred to the videoOutput object of the camera. let surfaceID; // The surface ID is obtained by calling getInputSurface and transferred to the videoOutput object of the camera.
await this.getFd('01.mp4'); await this.getFd('01.mp4');
// Configure the parameters related to audio and video recording. // Configure the parameters related to audio and video recording based on those supported by the hardware device.
let avProfile = { let avProfile = {
audioBitrate : 48000, audioBitrate : 48000,
audioChannels : 2, audioChannels : 2,
audioCodec : media.CodecMimeType.AUDIO_AAC, audioCodec : media.CodecMimeType.AUDIO_AAC,
audioSampleRate : 48000, audioSampleRate : 48000,
fileFormat : media.ContainerFormatType.CFT_MPEG_4, fileFormat : media.ContainerFormatType.CFT_MPEG_4,
videoBitrate : 48000, videoBitrate : 2000000,
videoCodec : media.CodecMimeType.VIDEO_MPEG4, videoCodec : media.CodecMimeType.VIDEO_MPEG4,
videoFrameWidth : 640, videoFrameWidth : 640,
videoFrameHeight : 480, videoFrameHeight : 480,
...@@ -365,10 +365,10 @@ export class VideoRecorderDemo { ...@@ -365,10 +365,10 @@ export class VideoRecorderDemo {
let surfaceID; // The surface ID is obtained by calling getInputSurface and transferred to the videoOutput object of the camera. let surfaceID; // The surface ID is obtained by calling getInputSurface and transferred to the videoOutput object of the camera.
await this.getFd('01.mp4'); await this.getFd('01.mp4');
// Configure the parameters related to video recording. // Configure the parameters related to pure video recording based on those supported by the hardware device.
let videoProfile = { let videoProfile = {
fileFormat : media.ContainerFormatType.CFT_MPEG_4, fileFormat : media.ContainerFormatType.CFT_MPEG_4,
videoBitrate : 48000, videoBitrate : 2000000,
videoCodec : media.CodecMimeType.VIDEO_MPEG4, videoCodec : media.CodecMimeType.VIDEO_MPEG4,
videoFrameWidth : 640, videoFrameWidth : 640,
videoFrameHeight : 480, videoFrameHeight : 480,
......
...@@ -51,7 +51,7 @@ For details about how to create an XComponent, see [XComponent](../reference/ark ...@@ -51,7 +51,7 @@ For details about how to create an XComponent, see [XComponent](../reference/ark
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
export class VideoPlayerDemo { export class VideoPlayerDemo {
// Report an error in the case of a function invocation failure. // Report an error in the case of a function invocation failure.
failureCallback(error) { failureCallback(error) {
...@@ -82,14 +82,8 @@ export class VideoPlayerDemo { ...@@ -82,14 +82,8 @@ export class VideoPlayerDemo {
let fdPath = 'fd://' let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4'; let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4';
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
// Call createVideoPlayer to create a VideoPlayer instance. // Call createVideoPlayer to create a VideoPlayer instance.
await media.createVideoPlayer().then((video) => { await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') { if (typeof (video) != 'undefined') {
...@@ -180,7 +174,7 @@ export class VideoPlayerDemo { ...@@ -180,7 +174,7 @@ export class VideoPlayerDemo {
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
export class VideoPlayerDemo { export class VideoPlayerDemo {
// Report an error in the case of a function invocation failure. // Report an error in the case of a function invocation failure.
failureCallback(error) { failureCallback(error) {
...@@ -211,14 +205,8 @@ export class VideoPlayerDemo { ...@@ -211,14 +205,8 @@ export class VideoPlayerDemo {
let fdPath = 'fd://' let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4'; let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4';
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
// Call createVideoPlayer to create a VideoPlayer instance. // Call createVideoPlayer to create a VideoPlayer instance.
await media.createVideoPlayer().then((video) => { await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') { if (typeof (video) != 'undefined') {
...@@ -267,7 +255,7 @@ export class VideoPlayerDemo { ...@@ -267,7 +255,7 @@ export class VideoPlayerDemo {
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
export class VideoPlayerDemo { export class VideoPlayerDemo {
// Report an error in the case of a function invocation failure. // Report an error in the case of a function invocation failure.
failureCallback(error) { failureCallback(error) {
...@@ -299,14 +287,8 @@ export class VideoPlayerDemo { ...@@ -299,14 +287,8 @@ export class VideoPlayerDemo {
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4'; let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4';
let nextPath = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/MP4_AAC.mp4'; let nextPath = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/MP4_AAC.mp4';
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
// Call createVideoPlayer to create a VideoPlayer instance. // Call createVideoPlayer to create a VideoPlayer instance.
await media.createVideoPlayer().then((video) => { await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') { if (typeof (video) != 'undefined') {
...@@ -341,14 +323,8 @@ export class VideoPlayerDemo { ...@@ -341,14 +323,8 @@ export class VideoPlayerDemo {
// Obtain the next video FD address. // Obtain the next video FD address.
fdPath = 'fd://' fdPath = 'fd://'
await fileIO.open(nextPath).then((fdNumber) => { let nextFile = await fs.open(nextPath);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + nextFile.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
// Set the second video playback source. // Set the second video playback source.
videoPlayer.url = fdPath; videoPlayer.url = fdPath;
...@@ -378,7 +354,7 @@ export class VideoPlayerDemo { ...@@ -378,7 +354,7 @@ export class VideoPlayerDemo {
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
export class VideoPlayerDemo { export class VideoPlayerDemo {
// Report an error in the case of a function invocation failure. // Report an error in the case of a function invocation failure.
failureCallback(error) { failureCallback(error) {
...@@ -409,14 +385,8 @@ export class VideoPlayerDemo { ...@@ -409,14 +385,8 @@ export class VideoPlayerDemo {
let fdPath = 'fd://' let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4'; let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4';
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
// Call createVideoPlayer to create a VideoPlayer instance. // Call createVideoPlayer to create a VideoPlayer instance.
await media.createVideoPlayer().then((video) => { await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') { if (typeof (video) != 'undefined') {
......
...@@ -76,14 +76,14 @@ export class VideoRecorderDemo { ...@@ -76,14 +76,14 @@ export class VideoRecorderDemo {
let surfaceID = null; // Used to save the surface ID returned by getInputSurface. let surfaceID = null; // Used to save the surface ID returned by getInputSurface.
// Obtain the FD address of the video to be recorded. // Obtain the FD address of the video to be recorded.
await this.getFd('01.mp4'); await this.getFd('01.mp4');
// Recording-related parameter settings // Configure the parameters related to video recording based on those supported by the hardware device.
let videoProfile = { let videoProfile = {
audioBitrate : 48000, audioBitrate : 48000,
audioChannels : 2, audioChannels : 2,
audioCodec : 'audio/mp4a-latm', audioCodec : 'audio/mp4a-latm',
audioSampleRate : 48000, audioSampleRate : 48000,
fileFormat : 'mp4', fileFormat : 'mp4',
videoBitrate : 48000, videoBitrate : 2000000,
videoCodec : 'video/mp4v-es', videoCodec : 'video/mp4v-es',
videoFrameWidth : 640, videoFrameWidth : 640,
videoFrameHeight : 480, videoFrameHeight : 480,
......
...@@ -4,9 +4,7 @@ OpenHarmony applications use JavaScript (JS) when calling native APIs. The nativ ...@@ -4,9 +4,7 @@ OpenHarmony applications use JavaScript (JS) when calling native APIs. The nativ
## How to Develop ## How to Develop
The DevEco Studio has a default project that uses NAPIs. The DevEco Studio has a default project that uses NAPIs. You can choose **File** > **New** > **Create Project** to create a **Native C++** project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **ace_napi** repository for development.
You can choose **File** > **New** > **Create Project** to create a **Native C++** project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **ace_napi** repository for development.
You can import the native .so that contains the JS processing logic. For example, **import hello from 'libhello.so'** to use the **libhello.so** capability. Then, the JS object created using the NAPI can be passed to the **hello** object of the application to call the native capability. You can import the native .so that contains the JS processing logic. For example, **import hello from 'libhello.so'** to use the **libhello.so** capability. Then, the JS object created using the NAPI can be passed to the **hello** object of the application to call the native capability.
...@@ -19,7 +17,10 @@ You can import the native .so that contains the JS processing logic. For example ...@@ -19,7 +17,10 @@ You can import the native .so that contains the JS processing logic. For example
### .so Naming Rules ### .so Naming Rules
Each module has a .so file. For example, if the module name is **hello**, name the .so file **libhello.so**. The **nm_modname** field in **napi_module** must be **hello**, which is the same as the module name. The sample code for importing the .so file is **import hello from 'libhello.so'**. The .so file names must comply with the following rules:
* Each module has a .so file.
* The **nm_modname** field in **napi_module** must be the same as the module name. For example, if the module name is **hello**, name the .so file **libhello.so**. The sample code for importing the .so file is **import hello from 'libhello.so'**.
### JS Objects and Threads ### JS Objects and Threads
......
...@@ -13,6 +13,7 @@ The **app** tag contains application-wide configuration. The internal structure ...@@ -13,6 +13,7 @@ The **app** tag contains application-wide configuration. The internal structure
| apiVersion | OpenHarmony API version on which the application depends.| Object| Yes (initial value: left empty)| | apiVersion | OpenHarmony API version on which the application depends.| Object| Yes (initial value: left empty)|
| smartWindowSize | Screen size used when the application runs in the emulator.| String| Yes (initial value: left empty)| | smartWindowSize | Screen size used when the application runs in the emulator.| String| Yes (initial value: left empty)|
| smartWindowDeviceType | Types of emulated devcies on which the application can run.| String array| Yes (initial value: left empty)| | smartWindowDeviceType | Types of emulated devcies on which the application can run.| String array| Yes (initial value: left empty)|
| assanEnabled | Whether to enable AddressSanitizer (ASan) to detect memory corruption issues such as buffer overflows.<br>- **true**: ASan is enabled.<br>- **false**: ASan is disabled. Note that ASan is not available in the Release version.| Boolean| Yes (initial value: **false**)|
## Internal Structure of the version Atttribute ## Internal Structure of the version Atttribute
......
...@@ -3,25 +3,27 @@ ...@@ -3,25 +3,27 @@
DevEco Studio allows you to develop and build multiple HAP files in one application project, as shown below. DevEco Studio allows you to develop and build multiple HAP files in one application project, as shown below.
**Figure 1** Multi-HAP build view
**Figure 1** Multi-HAP build view
![hap-multi-view](figures/hap-multi-view.png) ![hap-multi-view](figures/hap-multi-view.png)
1. Development view in DevEco Studio 1. Development view in DevEco Studio
- AppScope folder - **AppScope** folder
- [app.json5](app-configuration-file.md): application-wide configuration, such as the application bundle name, version number, application icon, application name, and dependent SDK version number.
- **[app.json5](app-configuration-file.md)**: stores application-wide configuration, such as the application bundle name, version number, application icon, application name, and dependent SDK version number.
- **resources** folder: stores application icon resources and application name string resources. - **resources** folder: stores application icon resources and application name string resources.
**NOTE** **NOTE**
- The folder is automatically generated by DevEco Studio and its name cannot be changed.
- The file names in the **AppScope** folder cannot be the same as those in the entry- or feature-type module directories. Otherwise, DevEco Studio reports an error. - The folder is automatically generated by DevEco Studio and its name cannot be changed.
- Entry- or feature-type module directories (the names are customizable) - The file names in the **AppScope** folder cannot be the same as those in the entry- or feature-type module folder. Otherwise, an error will be reported.
- You implement service logic of your application in these module directories. In this example, the module folders are **entry.hap** and **feature.hap**. - **entry** or **feature** folder (whose name is customizable)
- **resources** directory: stores the resources used by the module. - A module folder created by the developer by following the creation wizard of DevEco Studio. It stores the service logic implementation of the application. Multiple module folders can be created. In the preceding figure, **entry** and **feature** are two created module folders.
- **resources** folder: stores the resources used by the module.
- **ets** folder: stores the service logic. - **ets** folder: stores the service logic.
- [module.json5](module-configuration-file.md): module configuration, such as the module name, entry code path of the module, and component information. - **[module.json5](module-configuration-file.md)**: stores module configuration, such as the module name, entry code path of the module, and component information.
2. View after build and packaging 2. View after build and packaging
- After a module is built, a HAP file for deployment is generated. Each module corresponds to a HAP file. - After a module is built, a HAP file for deployment is generated. Each module corresponds to a HAP file.
- The **module.json** file in the HAP file is composed of the **app.json5** and **module.json5** files in the development view. - The **module.json** file in the HAP file is composed of the **app.json5** and **module.json5** files in the development view.
......
...@@ -6,32 +6,40 @@ Below is the process of developing, debugging, releasing, and deploying multiple ...@@ -6,32 +6,40 @@ Below is the process of developing, debugging, releasing, and deploying multiple
![hap-release](figures/hap-release.png) ![hap-release](figures/hap-release.png)
## Development ## Development
You can use [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio) to create multiple modules based on service requirements and develop services in independent modules. You can use [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio) to create multiple modules as needed and develop services in respective modules.
## Debugging ## Debugging
You can use DevEco Studio to build code into one or more HAP files. Then, you can debug the HAP files. After building code into one or more HAP files and installing or updating these HAP files, you can debug them by using the methods:
* Using DevEco Studio for debugging * Using DevEco Studio for debugging
Follow the instructions in [Debugging Configuration](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-debugging-and-running-0000001263040487#section10491183521520). Follow the instructions in [Debugging Configuration](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-debugging-and-running-0000001263040487#section10491183521520).
* Using [hdc_std](../../device-dev/subsystems/subsys-toolchain-hdc-guide.md) for debugging * Using [hdc](../../device-dev/subsystems/subsys-toolchain-hdc-guide.md) (which can be obtained in the **toolchains** directory of the OpenHarmony SDK) for debugging
Before debugging HAP files, install or update them using either of the methods:
1. Use hdc to install and update the HAP files.
When specifying the HAP files, use the paths of the files on the operating system, for example, Windows.
You can obtain the hdc_std tool from the **toolchains** directory of the SDK. When using this tool to install an HAP file, the HAP file path is the one on the operating platform. In this example, the Windows operating platform is used. The command reference is as follows:
``` ```
// Installation and update: Multiple file paths can be specified. // Installation and update: Multiple file paths can be specified.
hdc_std install C:\entry.hap C:\feature.hap hdc install C:\entry.hap C:\feature.hap
// The execution result is as follows: // The execution result is as follows:
install bundle successfully. install bundle successfully.
// Uninstall // Uninstall
hdc_std uninstall com.example.myapplication hdc uninstall com.example.myapplication
// The execution result is as follows: // The execution result is as follows:
uninstall bundle successfully. uninstall bundle successfully.
``` ```
2. Run the hdc shell command, and then use the Bundle Manager (bm) tool to install and update the HAP files.
* Using [Bundle Manager (bm)](../../application-dev/tools/bm-tool.md) for debugging When specifying the HAP files, use the paths of the files on the real device. The sample code is as follows:
When using bm to install or update an HAP file, the HAP file path is the one on the real device. The command reference is as follows:
``` ```
// Run the hdc shell command before using the bm tool.
hdc shell
// Installation and update: Multiple file paths can be specified. // Installation and update: Multiple file paths can be specified.
bm install -p /data/app/entry.hap /data/app/feature.hap bm install -p /data/app/entry.hap /data/app/feature.hap
// The execution result is as follows: // The execution result is as follows:
...@@ -41,6 +49,8 @@ You can use DevEco Studio to build code into one or more HAP files. Then, you ca ...@@ -41,6 +49,8 @@ You can use DevEco Studio to build code into one or more HAP files. Then, you ca
// The execution result is as follows: // The execution result is as follows:
uninstall bundle successfully. uninstall bundle successfully.
``` ```
After the HAP files are installed or updated, you can debug them by following the instructions in [Ability Assistant](https://docs.openharmony.cn/pages/v3.2Beta/en/application-dev/tools/aa-tool.md/).
## Release ## Release
When your application package meets the release requirements, you can package and build it into an App Pack and release it to the application market on the cloud. The application market verifies the signature of the App Pack. If the signature verification is successful, the application market obtains the HAP files from the App Pack, signs them, and distributes the signed HAP files. When your application package meets the release requirements, you can package and build it into an App Pack and release it to the application market on the cloud. The application market verifies the signature of the App Pack. If the signature verification is successful, the application market obtains the HAP files from the App Pack, signs them, and distributes the signed HAP files.
......
# Multi-HAP Usage Rules # Multi-HAP Usage Rules
- The App Pack cannot be directly installed on the device. It is only a unit that is released to AppGallery. - The App Pack cannot be directly installed on a device. It is only used to be released to the application market.
- All HAP files in the App Pack must share the same **bundleName** value in the configuration files. - All HAP files in the App Pack must share the same **bundleName** value in the configuration files.
- All HAP files in the App Pack must share the same **versionCode** value in the configuration files. - All HAP files in the App Pack must share the same **versionCode** value in the configuration files.
- In an application, each type of device supports only one HAP of the entry type. Each application can contain zero, one, or more HAP files of the feature type. - In an App Pack, each type of device supports only one HAP file of the entry type and zero, one, or more HAP files of the feature type.
- Each HAP file in the App Pack must have **moduleName** configured. The **moduleName** value corresponding to all HAP files of the same device type must be unique. - Each HAP file in the App Pack must have **moduleName** configured. Among HAP files of the same device type, the **moduleName** value must be unique.
- The signing certificates of all HAP files in the same application must be the same. Applications are released to the application market in the form of App Pack after being signed. Before distribution, the application market splits an App Pack into HAP files and resigns them to ensure the consistency of all HAP file signing certificates. Before installing HAP files on a device through the CLI or DevEco Studio for debugging, you must ensure that their signing certificates are the same. Otherwise, the installation will fail. - The signing certificates of all HAP files in the same application must be the same. Applications are released to the application market in the form of App Pack after being signed. Before distribution, the application market splits an App Pack into HAP files and resigns them to ensure the consistency of HAP file signing certificates. Before installing HAP files on a device through the CLI or DevEco Studio for debugging, ensure that their signing certificates are the same. Otherwise, the installation will fail.
...@@ -19,8 +19,6 @@ ...@@ -19,8 +19,6 @@
- [@ohos.application.DataShareExtensionAbility (DataShare Extension Ability)](js-apis-application-dataShareExtensionAbility.md) - [@ohos.application.DataShareExtensionAbility (DataShare Extension Ability)](js-apis-application-dataShareExtensionAbility.md)
- [@ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility)](js-apis-application-staticSubscriberExtensionAbility.md) - [@ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility)](js-apis-application-staticSubscriberExtensionAbility.md)
- Stage Model (To Be Deprecated Soon) - Stage Model (To Be Deprecated Soon)
- [@ohos.application.Ability (Ability)](js-apis-application-ability.md)
- [@ohos.application.AbilityLifecycleCallback (AbilityLifecycleCallback)](js-apis-application-abilityLifecycleCallback.md)
- [@ohos.application.EnvironmentCallback (EnvironmentCallback)](js-apis-application-environmentCallback.md) - [@ohos.application.EnvironmentCallback (EnvironmentCallback)](js-apis-application-environmentCallback.md)
- FA Model - FA Model
- [@ohos.ability.ability (Ability)](js-apis-ability-ability.md) - [@ohos.ability.ability (Ability)](js-apis-ability-ability.md)
...@@ -34,6 +32,7 @@ ...@@ -34,6 +32,7 @@
- [@ohos.app.ability.Configuration (Configuration)](js-apis-app-ability-configuration.md) - [@ohos.app.ability.Configuration (Configuration)](js-apis-app-ability-configuration.md)
- [@ohos.app.ability.ConfigurationConstant (ConfigurationConstant)](js-apis-app-ability-configurationConstant.md) - [@ohos.app.ability.ConfigurationConstant (ConfigurationConstant)](js-apis-app-ability-configurationConstant.md)
- [@ohos.app.ability.dataUriUtils (DataUriUtils)](js-apis-app-ability-dataUriUtils.md) - [@ohos.app.ability.dataUriUtils (DataUriUtils)](js-apis-app-ability-dataUriUtils.md)
- [@ohos.app.ability.dialogRequest (dialogRequest)](js-apis-app-ability-dialogRequest.md)
- [@ohos.app.ability.errorManager (ErrorManager)](js-apis-app-ability-errorManager.md) - [@ohos.app.ability.errorManager (ErrorManager)](js-apis-app-ability-errorManager.md)
- [@ohos.app.ability.missionManager (missionManager)](js-apis-app-ability-missionManager.md) - [@ohos.app.ability.missionManager (missionManager)](js-apis-app-ability-missionManager.md)
- [@ohos.app.ability.quickFixManager (quickFixManager)](js-apis-app-ability-quickFixManager.md) - [@ohos.app.ability.quickFixManager (quickFixManager)](js-apis-app-ability-quickFixManager.md)
...@@ -53,7 +52,6 @@ ...@@ -53,7 +52,6 @@
- [@ohos.application.appManager (appManager)](js-apis-application-appManager.md) - [@ohos.application.appManager (appManager)](js-apis-application-appManager.md)
- [@ohos.application.Configuration (Configuration)](js-apis-application-configuration.md) - [@ohos.application.Configuration (Configuration)](js-apis-application-configuration.md)
- [@ohos.application.ConfigurationConstant (ConfigurationConstant)](js-apis-application-configurationConstant.md) - [@ohos.application.ConfigurationConstant (ConfigurationConstant)](js-apis-application-configurationConstant.md)
- [@ohos.application.errorManager (ErrorManager)](js-apis-application-errorManager.md)
- [@ohos.application.formBindingData (formBindingData)](js-apis-application-formBindingData.md) - [@ohos.application.formBindingData (formBindingData)](js-apis-application-formBindingData.md)
- [@ohos.application.formError (FormError)](js-apis-application-formError.md) - [@ohos.application.formError (FormError)](js-apis-application-formError.md)
- [@ohos.application.formHost (FormHost)](js-apis-application-formHost.md) - [@ohos.application.formHost (FormHost)](js-apis-application-formHost.md)
...@@ -76,7 +74,6 @@ ...@@ -76,7 +74,6 @@
- [context](js-apis-inner-app-context.md) - [context](js-apis-inner-app-context.md)
- [processInfo](js-apis-inner-app-processInfo.md) - [processInfo](js-apis-inner-app-processInfo.md)
- application - application
- [AbilityContext](js-apis-ability-context.md)
- [abilityDelegator](js-apis-inner-application-abilityDelegator.md) - [abilityDelegator](js-apis-inner-application-abilityDelegator.md)
- [abilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) - [abilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md)
- [abilityMonitor](js-apis-inner-application-abilityMonitor.md) - [abilityMonitor](js-apis-inner-application-abilityMonitor.md)
...@@ -107,6 +104,7 @@ ...@@ -107,6 +104,7 @@
- [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) - [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md)
- [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) - [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md)
- [shellCmdResult](js-apis-inner-application-shellCmdResult.md) - [shellCmdResult](js-apis-inner-application-shellCmdResult.md)
- [WindowExtensionContext](js-apis-inner-application-windowExtensionContext.md)
- wantAgent - wantAgent
- [triggerInfo](js-apis-inner-wantAgent-triggerInfo.md) - [triggerInfo](js-apis-inner-wantAgent-triggerInfo.md)
- [wantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) - [wantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md)
...@@ -117,10 +115,12 @@ ...@@ -117,10 +115,12 @@
- [continuationResult](js-apis-continuation-continuationResult.md) - [continuationResult](js-apis-continuation-continuationResult.md)
- Common Event and Notification - Common Event and Notification
- [System Common Events](commonEventManager-definitions.md)
- [@ohos.commonEventManager (Common Event) (Recommended)](js-apis-commonEventManager.md) - [@ohos.commonEventManager (Common Event) (Recommended)](js-apis-commonEventManager.md)
- [@ohos.events.emitter (Emitter)](js-apis-emitter.md) - [@ohos.events.emitter (Emitter)](js-apis-emitter.md)
- [@ohos.notificationManager (NotificationManager) (Recommended)](js-apis-notificationManager.md) - [@ohos.notificationManager (NotificationManager) (Recommended)](js-apis-notificationManager.md)
- [@ohos.notificationSubscribe (NotificationSubscribe) (Recommended)](js-apis-notificationSubscribe.md) - [@ohos.notificationSubscribe (NotificationSubscribe) (Recommended)](js-apis-notificationSubscribe.md)
- [System Common Events (To Be Deprecated Soon)](commonEvent-definitions.md)
- [@ohos.commonEvent (Common Event) (To Be Deprecated Soon)](js-apis-commonEvent.md) - [@ohos.commonEvent (Common Event) (To Be Deprecated Soon)](js-apis-commonEvent.md)
- [@ohos.notification (Notification) (To Be Deprecated Soon)](js-apis-notification.md) - [@ohos.notification (Notification) (To Be Deprecated Soon)](js-apis-notification.md)
- application - application
...@@ -139,13 +139,13 @@ ...@@ -139,13 +139,13 @@
- [abilityInfo](js-apis-bundleManager-abilityInfo.md) - [abilityInfo](js-apis-bundleManager-abilityInfo.md)
- [applicationInfo](js-apis-bundleManager-applicationInfo.md) - [applicationInfo](js-apis-bundleManager-applicationInfo.md)
- [bundleInfo](js-apis-bundleManager-bundleInfo.md) - [bundleInfo](js-apis-bundleManager-bundleInfo.md)
- [BundlePackInfo](js-apis-bundleManager-BundlePackInfo.md)
- [dispatchInfo](js-apis-bundleManager-dispatchInfo.md) - [dispatchInfo](js-apis-bundleManager-dispatchInfo.md)
- [elementName](js-apis-bundleManager-elementName.md) - [elementName](js-apis-bundleManager-elementName.md)
- [extensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md) - [extensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md)
- [hapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) - [hapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)
- [launcherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) - [launcherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md)
- [metadata](js-apis-bundleManager-metadata.md) - [metadata](js-apis-bundleManager-metadata.md)
- [packInfo](js-apis-bundleManager-packInfo.md)
- [permissionDef](js-apis-bundleManager-permissionDef.md) - [permissionDef](js-apis-bundleManager-permissionDef.md)
- [remoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) - [remoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)
- [shortcutInfo](js-apis-bundleManager-shortcutInfo.md) - [shortcutInfo](js-apis-bundleManager-shortcutInfo.md)
...@@ -185,6 +185,7 @@ ...@@ -185,6 +185,7 @@
- [@ohos.resourceschedule.workScheduler (Work Scheduler)](js-apis-resourceschedule-workScheduler.md) - [@ohos.resourceschedule.workScheduler (Work Scheduler)](js-apis-resourceschedule-workScheduler.md)
- [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](js-apis-resourceschedule-deviceUsageStatistics.md) - [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](js-apis-resourceschedule-deviceUsageStatistics.md)
- [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](js-apis-WorkSchedulerExtensionAbility.md) - [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](js-apis-WorkSchedulerExtensionAbility.md)
- Security - Security
- [@ohos.abilityAccessCtrl (Ability Access Control)](js-apis-abilityAccessCtrl.md) - [@ohos.abilityAccessCtrl (Ability Access Control)](js-apis-abilityAccessCtrl.md)
- [@ohos.privacyManager (Privacy Management)](js-apis-privacyManager.md) - [@ohos.privacyManager (Privacy Management)](js-apis-privacyManager.md)
...@@ -216,10 +217,11 @@ ...@@ -216,10 +217,11 @@
- [@ohos.file.hash (File Hash Processing)](js-apis-file-hash.md) - [@ohos.file.hash (File Hash Processing)](js-apis-file-hash.md)
- [@ohos.file.securityLabel (Data Label)](js-apis-file-securityLabel.md) - [@ohos.file.securityLabel (Data Label)](js-apis-file-securityLabel.md)
- [@ohos.file.statvfs (File System Space Statistics)](js-apis-file-statvfs.md) - [@ohos.file.statvfs (File System Space Statistics)](js-apis-file-statvfs.md)
- [@ohos.filemanagement.userFileManager (User Data Management)](js-apis-userFileManager.md)
- [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md)
- [@ohos.file.storageStatistics (Application Storage Statistics)](js-apis-file-storage-statistics.md) - [@ohos.file.storageStatistics (Application Storage Statistics)](js-apis-file-storage-statistics.md)
- [@ohos.file.volumeManager (Volume Management)](js-apis-file-volumemanager.md) - [@ohos.file.volumeManager (Volume Management)](js-apis-file-volumemanager.md)
- [@ohos.filemanagement.userFileManager (User Data Management)](js-apis-userFileManager.md)
- [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md)
- Telephony Service - Telephony Service
- [@ohos.contact (Contacts)](js-apis-contact.md) - [@ohos.contact (Contacts)](js-apis-contact.md)
- [@ohos.telephony.call (Call)](js-apis-call.md) - [@ohos.telephony.call (Call)](js-apis-call.md)
...@@ -271,7 +273,7 @@ ...@@ -271,7 +273,7 @@
- [@ohos.InputMethodSubtype (Input Method Subtype)](js-apis-inputmethod-subtype.md) - [@ohos.InputMethodSubtype (Input Method Subtype)](js-apis-inputmethod-subtype.md)
- [@ohos.pasteboard (Pasteboard)](js-apis-pasteboard.md) - [@ohos.pasteboard (Pasteboard)](js-apis-pasteboard.md)
- [@ohos.screenLock (Screenlock)](js-apis-screen-lock.md) - [@ohos.screenLock (Screenlock)](js-apis-screen-lock.md)
- [@ohos.systemTime (System Time and Time Zone)](js-apis-system-time.md) - [@ohos.systemDateTime (System Time and Time Zone)](js-apis-system-date-time.md)
- [@ohos.systemTimer (System Timer)](js-apis-system-timer.md) - [@ohos.systemTimer (System Timer)](js-apis-system-timer.md)
- [@ohos.wallpaper (Wallpaper)](js-apis-wallpaper.md) - [@ohos.wallpaper (Wallpaper)](js-apis-wallpaper.md)
- [@ohos.web.webview (Webview)](js-apis-webview.md) - [@ohos.web.webview (Webview)](js-apis-webview.md)
...@@ -279,6 +281,9 @@ ...@@ -279,6 +281,9 @@
- [Timer](js-apis-timer.md) - [Timer](js-apis-timer.md)
- application - application
- [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md) - [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md)
- imf
- [InputMethodCommon](js-apis-inputmethod-InputMethodCommon.md)
- Device Management - Device Management
- [@ohos.batteryInfo (Battery Information)](js-apis-battery-info.md) - [@ohos.batteryInfo (Battery Information)](js-apis-battery-info.md)
- [@ohos.batteryStatistics (Battery Statistics)](js-apis-batteryStatistics.md) - [@ohos.batteryStatistics (Battery Statistics)](js-apis-batteryStatistics.md)
...@@ -314,10 +319,11 @@ ...@@ -314,10 +319,11 @@
- [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md) - [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md)
- Custom Management - Custom Management
- [@ohos.configPolicy (Configuration Policy)](js-apis-configPolicy.md) - [@ohos.configPolicy (Configuration Policy)](js-apis-configPolicy.md)
- [@ohos.enterprise.deviceInfo (Device Information Management)](js-apis-enterprise-deviceInfo.md)
- [@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](js-apis-EnterpriseAdminExtensionAbility.md)
- [@ohos.enterprise.adminManager (Enterprise Device Management)](js-apis-enterprise-adminManager.md) - [@ohos.enterprise.adminManager (Enterprise Device Management)](js-apis-enterprise-adminManager.md)
- [@ohos.enterprise.dateTimeManager (System Time Management)](js-apis-enterprise-dateTimeManager.md) - [@ohos.enterprise.dateTimeManager (System Time Management)](js-apis-enterprise-dateTimeManager.md)
- [@ohos.enterprise.deviceControl (Device Control Management)](js-apis-enterprise-deviceControl.md)
- [@ohos.enterprise.deviceInfo (Device Information Management)](js-apis-enterprise-deviceInfo.md)
- [@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](js-apis-EnterpriseAdminExtensionAbility.md)
- Language Base Class Library - Language Base Class Library
- [@ohos.buffer (Buffer)](js-apis-buffer.md) - [@ohos.buffer (Buffer)](js-apis-buffer.md)
...@@ -364,6 +370,7 @@ ...@@ -364,6 +370,7 @@
- [@ohos.reminderAgent (Reminder Agent)](js-apis-reminderAgent.md) - [@ohos.reminderAgent (Reminder Agent)](js-apis-reminderAgent.md)
- [@ohos.statfs (statfs)](js-apis-statfs.md) - [@ohos.statfs (statfs)](js-apis-statfs.md)
- [@ohos.systemParameter (System Parameter)](js-apis-system-parameter.md) - [@ohos.systemParameter (System Parameter)](js-apis-system-parameter.md)
- [@ohos.systemTime (System Time and Time Zone)](js-apis-system-time.md)
- [@ohos.usb (USB Management)](js-apis-usb-deprecated.md) - [@ohos.usb (USB Management)](js-apis-usb-deprecated.md)
- [@ohos.usbV9 (USB Management)](js-apis-usb.md) - [@ohos.usbV9 (USB Management)](js-apis-usb.md)
- [@system.app (Application Context)](js-apis-system-app.md) - [@system.app (Application Context)](js-apis-system-app.md)
......
...@@ -1230,7 +1230,7 @@ SystemCapability.BundleManager.BundleFramework ...@@ -1230,7 +1230,7 @@ SystemCapability.BundleManager.BundleFramework
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------------------------- | ---- | ----------------------- | | -------- | -------------------------------------------- | ---- | ----------------------- |
| info | [AbilityInfo](js-apis-bundle-AbilityInfo.md) | Yes | Ability information. | | info | [AbilityInfo](js-apis-bundle-AbilityInfo.md) | Yes | Ability information. |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that the ability is enabled, and **false** means the opposite.| | callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.|
**Example** **Example**
...@@ -1603,7 +1603,7 @@ bundle.getNameForUid(uid, (err, data) => { ...@@ -1603,7 +1603,7 @@ bundle.getNameForUid(uid, (err, data) => {
## bundle.getAbilityIcon<sup>8+</sup> <sup>deprecated<sup> ## bundle.getAbilityIcon<sup>8+</sup> <sup>deprecated<sup>
> This API is deprecated since API version 9. You are advised to use [bundleManager.getAbilityIcon](js-apis-bundleManager.md#bundlemanagergetabilityicon) instead. > This API is deprecated since API version 9. You are advised to use [resourceManager.getMediaContent](js-apis-resource-manager.md#getmediacontent9) instead.
getAbilityIcon(bundleName: string, abilityName: string): Promise\<image.PixelMap>; getAbilityIcon(bundleName: string, abilityName: string): Promise\<image.PixelMap>;
...@@ -1646,7 +1646,7 @@ bundle.getAbilityIcon(bundleName, abilityName) ...@@ -1646,7 +1646,7 @@ bundle.getAbilityIcon(bundleName, abilityName)
## bundle.getAbilityIcon<sup>8+</sup> <sup>deprecated<sup> ## bundle.getAbilityIcon<sup>8+</sup> <sup>deprecated<sup>
> This API is deprecated since API version 9. You are advised to use [bundleManager.getAbilityIcon](js-apis-bundleManager.md#bundlemanagergetabilityicon) instead. > This API is deprecated since API version 9. You are advised to use [resourceManager.getMediaContent](js-apis-resource-manager.md#getmediacontent9) instead.
getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\<image.PixelMap>): void; getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\<image.PixelMap>): void;
......
...@@ -16,6 +16,14 @@ When developing an application, you can override the APIs of this module and add ...@@ -16,6 +16,14 @@ When developing an application, you can override the APIs of this module and add
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility' import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'
``` ```
## Attributes
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| context | [WorkSchedulerExtensionContext](js-apis-inner-application-WorkSchedulerExtensionContext.md) | Yes| No| Context of the **WorkSchedulerExtension**. This context is inherited from **ExtensionContext**.|
## WorkSchedulerExtensionAbility.onWorkStart ## WorkSchedulerExtensionAbility.onWorkStart
onWorkStart(work: workScheduler.WorkInfo): void onWorkStart(work: workScheduler.WorkInfo): void
......
...@@ -72,13 +72,13 @@ const config = { ...@@ -72,13 +72,13 @@ const config = {
try { try {
abilityManager.updateConfiguration(config, (err) => { abilityManager.updateConfiguration(config, (err) => {
if (err && err.code !== 0) { if (err && err.code !== 0) {
console.log('updateConfiguration fail, err: ${JSON.stringify(err)}'); console.error('updateConfiguration fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('updateConfiguration success.'); console.log('updateConfiguration success.');
} }
}); });
} catch (paramError) { } catch (paramError) {
console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}');
} }
``` ```
...@@ -130,10 +130,10 @@ try { ...@@ -130,10 +130,10 @@ try {
abilityManager.updateConfiguration(config).then(() => { abilityManager.updateConfiguration(config).then(() => {
console.log('updateConfiguration success.'); console.log('updateConfiguration success.');
}).catch((err) => { }).catch((err) => {
console.log('updateConfiguration fail, err: ${JSON.stringify(err)}'); console.error('updateConfiguration fail, err: ${JSON.stringify(err)}');
}); });
} catch (paramError) { } catch (paramError) {
console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}');
} }
``` ```
...@@ -169,13 +169,13 @@ import abilityManager from '@ohos.app.ability.abilityManager'; ...@@ -169,13 +169,13 @@ import abilityManager from '@ohos.app.ability.abilityManager';
try { try {
abilityManager.getAbilityRunningInfos((err, data) => { abilityManager.getAbilityRunningInfos((err, data) => {
if (err && err.code !== 0) { if (err && err.code !== 0) {
console.log('getAbilityRunningInfos fail, error: ${JSON.stringify(err)}'); console.error('getAbilityRunningInfos fail, error: ${JSON.stringify(err)}');
} else { } else {
console.log('getAbilityRunningInfos success, data: ${JSON.stringify(data)}'); console.log('getAbilityRunningInfos success, data: ${JSON.stringify(data)}');
} }
}); });
} catch (paramError) { } catch (paramError) {
console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}');
} }
``` ```
...@@ -212,10 +212,10 @@ try { ...@@ -212,10 +212,10 @@ try {
abilityManager.getAbilityRunningInfos().then((data) => { abilityManager.getAbilityRunningInfos().then((data) => {
console.log('getAbilityRunningInfos success, data: ${JSON.stringify(data)}'); console.log('getAbilityRunningInfos success, data: ${JSON.stringify(data)}');
}).catch((err) => { }).catch((err) => {
console.log('getAbilityRunningInfos fail, err: ${JSON.stringify(err)}'); console.error('getAbilityRunningInfos fail, err: ${JSON.stringify(err)}');
}); });
} catch (paramError) { } catch (paramError) {
console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}');
} }
``` ```
...@@ -254,13 +254,13 @@ let upperLimit = 10; ...@@ -254,13 +254,13 @@ let upperLimit = 10;
try { try {
abilityManager.getExtensionRunningInfos(upperLimit, (err, data) => { abilityManager.getExtensionRunningInfos(upperLimit, (err, data) => {
if (err && err.code !== 0) { if (err && err.code !== 0) {
console.log('getExtensionRunningInfos fail, err: ${JSON.stringify(err)}'); console.error('getExtensionRunningInfos fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('getExtensionRunningInfos success, data: ${JSON.stringify(data)}'); console.log('getExtensionRunningInfos success, data: ${JSON.stringify(data)}');
} }
}); });
} catch (paramError) { } catch (paramError) {
console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}');
} }
``` ```
...@@ -305,10 +305,10 @@ try { ...@@ -305,10 +305,10 @@ try {
abilityManager.getExtensionRunningInfos(upperLimit).then((data) => { abilityManager.getExtensionRunningInfos(upperLimit).then((data) => {
console.log('getExtensionRunningInfos success, data: ${JSON.stringify(data)}'); console.log('getExtensionRunningInfos success, data: ${JSON.stringify(data)}');
}).catch((err) => { }).catch((err) => {
console.log('getExtensionRunningInfos fail, err: ${JSON.stringify(err)}'); console.error('getExtensionRunningInfos fail, err: ${JSON.stringify(err)}');
}); });
} catch (paramError) { } catch (paramError) {
console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}');
} }
``` ```
...@@ -341,7 +341,7 @@ import abilityManager from '@ohos.app.ability.abilityManager'; ...@@ -341,7 +341,7 @@ import abilityManager from '@ohos.app.ability.abilityManager';
abilityManager.getTopAbility((err, data) => { abilityManager.getTopAbility((err, data) => {
if (err && err.code !== 0) { if (err && err.code !== 0) {
console.log('getTopAbility fail, err: ${JSON.stringify(err)}'); console.error('getTopAbility fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('getTopAbility success, data: ${JSON.stringify(data)}'); console.log('getTopAbility success, data: ${JSON.stringify(data)}');
} }
...@@ -378,6 +378,6 @@ import abilityManager from '@ohos.app.ability.abilityManager'; ...@@ -378,6 +378,6 @@ import abilityManager from '@ohos.app.ability.abilityManager';
abilityManager.getTopAbility().then((data) => { abilityManager.getTopAbility().then((data) => {
console.log('getTopAbility success, data: ${JSON.stringify(data)}'); console.log('getTopAbility success, data: ${JSON.stringify(data)}');
}).catch((err) => { }).catch((err) => {
console.log('getTopAbility fail, err: ${JSON.stringify(err)}'); console.error('getTopAbility fail, err: ${JSON.stringify(err)}');
}); });
``` ```
...@@ -41,7 +41,7 @@ import appManager from '@ohos.app.ability.appManager'; ...@@ -41,7 +41,7 @@ import appManager from '@ohos.app.ability.appManager';
appManager.isRunningInStabilityTest((err, flag) => { appManager.isRunningInStabilityTest((err, flag) => {
if (err && err.code !== 0) { if (err && err.code !== 0) {
console.log('isRunningInStabilityTest fail, err: ${JSON.stringify(err)}'); console.error('isRunningInStabilityTest fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}'); console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}');
} }
...@@ -79,7 +79,7 @@ import appManager from '@ohos.app.ability.appManager'; ...@@ -79,7 +79,7 @@ import appManager from '@ohos.app.ability.appManager';
appManager.isRunningInStabilityTest().then((flag) => { appManager.isRunningInStabilityTest().then((flag) => {
console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}'); console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}');
}).catch((error) => { }).catch((error) => {
console.log('error: ${JSON.stringify(error)}'); console.error('error: ${JSON.stringify(error)}');
}); });
``` ```
...@@ -114,7 +114,7 @@ import appManager from '@ohos.app.ability.appManager'; ...@@ -114,7 +114,7 @@ import appManager from '@ohos.app.ability.appManager';
appManager.isRamConstrainedDevice().then((data) => { appManager.isRamConstrainedDevice().then((data) => {
console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}'); console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}');
}).catch((error) => { }).catch((error) => {
console.log('error: ${JSON.stringify(error)}'); console.error('error: ${JSON.stringify(error)}');
}); });
``` ```
...@@ -147,7 +147,7 @@ import appManager from '@ohos.app.ability.appManager'; ...@@ -147,7 +147,7 @@ import appManager from '@ohos.app.ability.appManager';
appManager.isRamConstrainedDevice((err, data) => { appManager.isRamConstrainedDevice((err, data) => {
if (err && err.code !== 0) { if (err && err.code !== 0) {
console.log('isRamConstrainedDevice fail, err: ${JSON.stringify(err)}'); console.error('isRamConstrainedDevice fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}'); console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}');
} }
...@@ -184,7 +184,7 @@ import appManager from '@ohos.app.ability.appManager'; ...@@ -184,7 +184,7 @@ import appManager from '@ohos.app.ability.appManager';
appManager.getAppMemorySize().then((data) => { appManager.getAppMemorySize().then((data) => {
console.log('The size of app memory is: ${JSON.stringify(data)}'); console.log('The size of app memory is: ${JSON.stringify(data)}');
}).catch((error) => { }).catch((error) => {
console.log('error: ${JSON.stringify(error)}'); console.error('error: ${JSON.stringify(error)}');
}); });
``` ```
...@@ -217,7 +217,7 @@ import appManager from '@ohos.app.ability.appManager'; ...@@ -217,7 +217,7 @@ import appManager from '@ohos.app.ability.appManager';
appManager.getAppMemorySize((err, data) => { appManager.getAppMemorySize((err, data) => {
if (err && err.code !== 0) { if (err && err.code !== 0) {
console.log('getAppMemorySize fail, err: ${JSON.stringify(err)}'); console.error('getAppMemorySize fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('The size of app memory is: ${JSON.stringify(data)}'); console.log('The size of app memory is: ${JSON.stringify(data)}');
} }
...@@ -256,7 +256,7 @@ import appManager from '@ohos.app.ability.appManager'; ...@@ -256,7 +256,7 @@ import appManager from '@ohos.app.ability.appManager';
appManager.getRunningProcessInformation().then((data) => { appManager.getRunningProcessInformation().then((data) => {
console.log('The running process information is: ${JSON.stringify(data)}'); console.log('The running process information is: ${JSON.stringify(data)}');
}).catch((error) => { }).catch((error) => {
console.log('error: ${JSON.stringify(error)}'); console.error('error: ${JSON.stringify(error)}');
}); });
``` ```
...@@ -291,7 +291,7 @@ import appManager from '@ohos.app.ability.appManager'; ...@@ -291,7 +291,7 @@ import appManager from '@ohos.app.ability.appManager';
appManager.getRunningProcessInformation((err, data) => { appManager.getRunningProcessInformation((err, data) => {
if (err && err.code !== 0) { if (err && err.code !== 0) {
console.log('getRunningProcessInformation fail, err: ${JSON.stringify(err)}'); console.error('getRunningProcessInformation fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('The process running information is: ${JSON.stringify(data)}'); console.log('The process running information is: ${JSON.stringify(data)}');
} }
...@@ -357,7 +357,7 @@ try { ...@@ -357,7 +357,7 @@ try {
const observerId = appManager.on('applicationState', applicationStateObserver); const observerId = appManager.on('applicationState', applicationStateObserver);
console.log(`[appManager] observerCode: ${observerId}`); console.log(`[appManager] observerCode: ${observerId}`);
} catch (paramError) { } catch (paramError) {
console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `); console.error(`[appManager] error: ${paramError.code}, ${paramError.message} `);
} }
``` ```
...@@ -422,7 +422,7 @@ try { ...@@ -422,7 +422,7 @@ try {
const observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); const observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList);
console.log(`[appManager] observerCode: ${observerId}`); console.log(`[appManager] observerCode: ${observerId}`);
} catch (paramError) { } catch (paramError) {
console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `); console.error(`[appManager] error: ${paramError.code}, ${paramError.message} `);
} }
``` ```
...@@ -484,13 +484,13 @@ try { ...@@ -484,13 +484,13 @@ try {
observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList);
console.log(`[appManager] observerCode: ${observerId}`); console.log(`[appManager] observerCode: ${observerId}`);
} catch (paramError) { } catch (paramError) {
console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `); console.error(`[appManager] error: ${paramError.code}, ${paramError.message} `);
} }
// 2. Deregister the application state observer. // 2. Deregister the application state observer.
function unregisterApplicationStateObserverCallback(err) { function unregisterApplicationStateObserverCallback(err) {
if (err && err.code !== 0) { if (err && err.code !== 0) {
console.log('unregisterApplicationStateObserverCallback fail, err: ${JSON.stringify(err)}'); console.error('unregisterApplicationStateObserverCallback fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('unregisterApplicationStateObserverCallback success.'); console.log('unregisterApplicationStateObserverCallback success.');
} }
...@@ -498,7 +498,7 @@ function unregisterApplicationStateObserverCallback(err) { ...@@ -498,7 +498,7 @@ function unregisterApplicationStateObserverCallback(err) {
try { try {
appManager.off('applicationState', observerId, unregisterApplicationStateObserverCallback); appManager.off('applicationState', observerId, unregisterApplicationStateObserverCallback);
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
``` ```
...@@ -565,7 +565,7 @@ try { ...@@ -565,7 +565,7 @@ try {
observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList);
console.log(`[appManager] observerCode: ${observerId}`); console.log(`[appManager] observerCode: ${observerId}`);
} catch (paramError) { } catch (paramError) {
console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `); console.error(`[appManager] error: ${paramError.code}, ${paramError.message} `);
} }
// 2. Deregister the application state observer. // 2. Deregister the application state observer.
...@@ -573,10 +573,10 @@ try { ...@@ -573,10 +573,10 @@ try {
appManager.off('applicationState', observerId).then((data) => { appManager.off('applicationState', observerId).then((data) => {
console.log('unregisterApplicationStateObserver success, data: ${JSON.stringify(data)}'); console.log('unregisterApplicationStateObserver success, data: ${JSON.stringify(data)}');
}).catch((err) => { }).catch((err) => {
console.log('unregisterApplicationStateObserver fail, err: ${JSON.stringify(err)}'); console.error('unregisterApplicationStateObserver fail, err: ${JSON.stringify(err)}');
}); });
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
``` ```
...@@ -613,7 +613,7 @@ import appManager from '@ohos.app.ability.appManager'; ...@@ -613,7 +613,7 @@ import appManager from '@ohos.app.ability.appManager';
function getForegroundApplicationsCallback(err, data) { function getForegroundApplicationsCallback(err, data) {
if (err && err.code !== 0) { if (err && err.code !== 0) {
console.log('getForegroundApplicationsCallback fail, err: ${JSON.stringify(err)}'); console.error('getForegroundApplicationsCallback fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('getForegroundApplicationsCallback success, data: ${JSON.stringify(data)}'); console.log('getForegroundApplicationsCallback success, data: ${JSON.stringify(data)}');
} }
...@@ -621,7 +621,7 @@ function getForegroundApplicationsCallback(err, data) { ...@@ -621,7 +621,7 @@ function getForegroundApplicationsCallback(err, data) {
try { try {
appManager.getForegroundApplications(getForegroundApplicationsCallback); appManager.getForegroundApplications(getForegroundApplicationsCallback);
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
``` ```
...@@ -659,7 +659,7 @@ import appManager from '@ohos.app.ability.appManager'; ...@@ -659,7 +659,7 @@ import appManager from '@ohos.app.ability.appManager';
appManager.getForegroundApplications().then((data) => { appManager.getForegroundApplications().then((data) => {
console.log('getForegroundApplications success, data: ${JSON.stringify(data)}'); console.log('getForegroundApplications success, data: ${JSON.stringify(data)}');
}).catch((err) => { }).catch((err) => {
console.log('getForegroundApplications fail, err: ${JSON.stringify(err)}'); console.error('getForegroundApplications fail, err: ${JSON.stringify(err)}');
}); });
``` ```
...@@ -746,7 +746,7 @@ let bundleName = 'bundleName'; ...@@ -746,7 +746,7 @@ let bundleName = 'bundleName';
let accountId = 0; let accountId = 0;
function killProcessWithAccountCallback(err, data) { function killProcessWithAccountCallback(err, data) {
if (err && err.code !== 0) { if (err && err.code !== 0) {
console.log('killProcessWithAccountCallback fail, err: ${JSON.stringify(err)}'); console.error('killProcessWithAccountCallback fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('killProcessWithAccountCallback success.'); console.log('killProcessWithAccountCallback success.');
} }
...@@ -789,7 +789,7 @@ import appManager from '@ohos.app.ability.appManager'; ...@@ -789,7 +789,7 @@ import appManager from '@ohos.app.ability.appManager';
let bundleName = 'bundleName'; let bundleName = 'bundleName';
function killProcessesByBundleNameCallback(err, data) { function killProcessesByBundleNameCallback(err, data) {
if (err && err.code !== 0) { if (err && err.code !== 0) {
console.log('killProcessesByBundleNameCallback fail, err: ${JSON.stringify(err)}'); console.error('killProcessesByBundleNameCallback fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('killProcessesByBundleNameCallback success.'); console.log('killProcessesByBundleNameCallback success.');
} }
...@@ -797,7 +797,7 @@ function killProcessesByBundleNameCallback(err, data) { ...@@ -797,7 +797,7 @@ function killProcessesByBundleNameCallback(err, data) {
try { try {
appManager.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); appManager.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback);
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
``` ```
...@@ -843,10 +843,10 @@ try { ...@@ -843,10 +843,10 @@ try {
appManager.killProcessesByBundleName(bundleName).then((data) => { appManager.killProcessesByBundleName(bundleName).then((data) => {
console.log('killProcessesByBundleName success.'); console.log('killProcessesByBundleName success.');
}).catch((err) => { }).catch((err) => {
console.log('killProcessesByBundleName fail, err: ${JSON.stringify(err)}'); console.error('killProcessesByBundleName fail, err: ${JSON.stringify(err)}');
}); });
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
``` ```
...@@ -885,7 +885,7 @@ import appManager from '@ohos.app.ability.appManager'; ...@@ -885,7 +885,7 @@ import appManager from '@ohos.app.ability.appManager';
let bundleName = 'bundleName'; let bundleName = 'bundleName';
function clearUpApplicationDataCallback(err, data) { function clearUpApplicationDataCallback(err, data) {
if (err && err.code !== 0) { if (err && err.code !== 0) {
console.log('clearUpApplicationDataCallback fail, err: ${JSON.stringify(err)}'); console.error('clearUpApplicationDataCallback fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('clearUpApplicationDataCallback success.'); console.log('clearUpApplicationDataCallback success.');
} }
...@@ -893,7 +893,7 @@ function clearUpApplicationDataCallback(err, data) { ...@@ -893,7 +893,7 @@ function clearUpApplicationDataCallback(err, data) {
try { try {
appManager.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); appManager.clearUpApplicationData(bundleName, clearUpApplicationDataCallback);
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
``` ```
...@@ -939,10 +939,10 @@ try { ...@@ -939,10 +939,10 @@ try {
appManager.clearUpApplicationData(bundleName).then((data) => { appManager.clearUpApplicationData(bundleName).then((data) => {
console.log('clearUpApplicationData success.'); console.log('clearUpApplicationData success.');
}).catch((err) => { }).catch((err) => {
console.log('clearUpApplicationData fail, err: ${JSON.stringify(err)}'); console.error('clearUpApplicationData fail, err: ${JSON.stringify(err)}');
}); });
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
``` ```
......
...@@ -42,7 +42,7 @@ export default class EntryAbility extends UIAbility { ...@@ -42,7 +42,7 @@ export default class EntryAbility extends UIAbility {
let callbackId = applicationContext.on('environment', envCallback); let callbackId = applicationContext.on('environment', envCallback);
console.log('callbackId: ${callbackId}'); console.log('callbackId: ${callbackId}');
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
} }
} }
......
...@@ -73,7 +73,11 @@ export default class MyAbility extends UIAbility { ...@@ -73,7 +73,11 @@ export default class MyAbility extends UIAbility {
onDestroy() { onDestroy() {
let applicationContext = globalThis.applicationContext; let applicationContext = globalThis.applicationContext;
applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => {
console.log('unregisterEnvironmentCallback success, err: ${JSON.stringify(error)}'); if (error && error.code !== 0) {
console.error('unregisterEnvironmentCallback fail, error: ${JSON.stringify(error)}');
} else {
console.log('unregisterEnvironmentCallback success, data: ${JSON.stringify(data)}');
}
}); });
} }
} }
......
...@@ -44,7 +44,7 @@ let observerId = -1; ...@@ -44,7 +44,7 @@ let observerId = -1;
try { try {
observerId = errorManager.on('error', observer); observerId = errorManager.on('error', observer);
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
``` ```
...@@ -71,13 +71,13 @@ let observerId = 100; ...@@ -71,13 +71,13 @@ let observerId = 100;
function unregisterErrorObserverCallback(err) { function unregisterErrorObserverCallback(err) {
if (err) { if (err) {
console.log('------------ unregisterErrorObserverCallback ------------', err); console.error('------------ unregisterErrorObserverCallback ------------', err);
} }
} }
try { try {
errorManager.off('error', observerId, unregisterErrorObserverCallback); errorManager.off('error', observerId, unregisterErrorObserverCallback);
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
``` ```
...@@ -112,10 +112,10 @@ try { ...@@ -112,10 +112,10 @@ try {
console.log('----------- unregisterErrorObserver success ----------', data); console.log('----------- unregisterErrorObserver success ----------', data);
}) })
.catch((err) => { .catch((err) => {
console.log('----------- unregisterErrorObserver fail ----------', err); console.error('----------- unregisterErrorObserver fail ----------', err);
}); });
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
``` ```
...@@ -73,7 +73,7 @@ export default class EntryAbility extends UIAbility { ...@@ -73,7 +73,7 @@ export default class EntryAbility extends UIAbility {
}); });
} }
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
console.log('[Demo] EntryAbility onDestroy'); console.log('[Demo] EntryAbility onDestroy');
} }
...@@ -84,7 +84,7 @@ export default class EntryAbility extends UIAbility { ...@@ -84,7 +84,7 @@ export default class EntryAbility extends UIAbility {
try { try {
listenerId = missionManager.on('mission', listener); listenerId = missionManager.on('mission', listener);
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
windowStage.loadContent('pages/index', (err, data) => { windowStage.loadContent('pages/index', (err, data) => {
...@@ -155,7 +155,7 @@ export default class EntryAbility extends UIAbility { ...@@ -155,7 +155,7 @@ export default class EntryAbility extends UIAbility {
}); });
} }
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
console.log('[Demo] EntryAbility onDestroy'); console.log('[Demo] EntryAbility onDestroy');
} }
...@@ -166,7 +166,7 @@ export default class EntryAbility extends UIAbility { ...@@ -166,7 +166,7 @@ export default class EntryAbility extends UIAbility {
try { try {
listenerId = missionManager.on('mission', listener); listenerId = missionManager.on('mission', listener);
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
windowStage.loadContent('pages/index', (err, data) => { windowStage.loadContent('pages/index', (err, data) => {
...@@ -242,7 +242,7 @@ export default class EntryAbility extends UIAbility { ...@@ -242,7 +242,7 @@ export default class EntryAbility extends UIAbility {
}); });
} }
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
console.log('[Demo] EntryAbility onDestroy'); console.log('[Demo] EntryAbility onDestroy');
} }
...@@ -253,7 +253,7 @@ export default class EntryAbility extends UIAbility { ...@@ -253,7 +253,7 @@ export default class EntryAbility extends UIAbility {
try { try {
listenerId = missionManager.on('mission', listener); listenerId = missionManager.on('mission', listener);
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
windowStage.loadContent('pages/index', (err, data) => { windowStage.loadContent('pages/index', (err, data) => {
...@@ -306,7 +306,7 @@ Obtains the information about a given mission. This API uses an asynchronous cal ...@@ -306,7 +306,7 @@ Obtains the information about a given mission. This API uses an asynchronous cal
missionManager.getMissionInfo('', testMissionId, (error, mission) => { missionManager.getMissionInfo('', testMissionId, (error, mission) => {
if (error) { if (error) {
console.log('getMissionInfo failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); console.error('getMissionInfo failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}');
} else { } else {
console.log('mission.missionId = ${mission.missionId}'); console.log('mission.missionId = ${mission.missionId}');
console.log('mission.runningState = ${mission.runningState}'); console.log('mission.runningState = ${mission.runningState}');
...@@ -317,7 +317,7 @@ Obtains the information about a given mission. This API uses an asynchronous cal ...@@ -317,7 +317,7 @@ Obtains the information about a given mission. This API uses an asynchronous cal
} }
}); });
} catch (paramError) { } catch (paramError) {
console.log('error.code: ${paramError.code}, error.message: ${paramError.message}'); console.error('error.code: ${paramError.code}, error.message: ${paramError.message}');
} }
``` ```
...@@ -392,14 +392,14 @@ Obtains information about all missions. This API uses an asynchronous callback t ...@@ -392,14 +392,14 @@ Obtains information about all missions. This API uses an asynchronous callback t
try { try {
missionManager.getMissionInfos('', 10, (error, missions) => { missionManager.getMissionInfos('', 10, (error, missions) => {
if (error) { if (error) {
console.log('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); console.error('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}');
} else { } else {
console.log('size = ${missions.length}'); console.log('size = ${missions.length}');
console.log('missions = ${JSON.stringify(missions)}'); console.log('missions = ${JSON.stringify(missions)}');
} }
}); });
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
``` ```
......
...@@ -57,10 +57,10 @@ Applies a quick fix patch. This API uses an asynchronous callback to return the ...@@ -57,10 +57,10 @@ Applies a quick fix patch. This API uses an asynchronous callback to return the
**Parameters** **Parameters**
| Parameter| Type| Mandatory| Description| | Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| hapModuleQuickFixFiles | Array\<string> | Yes| Quick fix patch files, each of which must contain a valid file path.| | hapModuleQuickFixFiles | Array\<string> | Yes| Quick fix patch files, each of which must contain a valid file path.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.| | callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
> **NOTE** > **NOTE**
> >
...@@ -73,13 +73,13 @@ Applies a quick fix patch. This API uses an asynchronous callback to return the ...@@ -73,13 +73,13 @@ Applies a quick fix patch. This API uses an asynchronous callback to return the
let hapModuleQuickFixFiles = ['/data/storage/el2/base/entry.hqf']; let hapModuleQuickFixFiles = ['/data/storage/el2/base/entry.hqf'];
quickFixManager.applyQuickFix(hapModuleQuickFixFiles, (error) => { quickFixManager.applyQuickFix(hapModuleQuickFixFiles, (error) => {
if (error) { if (error) {
console.info( `applyQuickFix failed with error: ${error}`); console.error( `applyQuickFix failed with error: ${error}`);
} else { } else {
console.info( 'applyQuickFix success'); console.info( 'applyQuickFix success');
} }
}); });
} catch (paramError) { } catch (paramError) {
console.log('error.code: ${paramError.code}, error.message: ${paramError.message}'); console.error('error.code: ${paramError.code}, error.message: ${paramError.message}');
} }
``` ```
...@@ -97,15 +97,15 @@ Applies a quick fix patch. This API uses a promise to return the result. ...@@ -97,15 +97,15 @@ Applies a quick fix patch. This API uses a promise to return the result.
**Parameters** **Parameters**
| Parameter| Type| Mandatory| Description| | Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| hapModuleQuickFixFiles | Array\<string> | Yes| Quick fix patch files, each of which must contain a valid file path.| | hapModuleQuickFixFiles | Array\<string> | Yes| Quick fix patch files, each of which must contain a valid file path.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | Promise used to return the result.|
**Example** **Example**
...@@ -115,10 +115,10 @@ Applies a quick fix patch. This API uses a promise to return the result. ...@@ -115,10 +115,10 @@ Applies a quick fix patch. This API uses a promise to return the result.
quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => { quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => {
console.info('applyQuickFix success'); console.info('applyQuickFix success');
}).catch((error) => { }).catch((error) => {
console.info(`applyQuickFix err: ${error}`); console.error(`applyQuickFix err: ${error}`);
}); });
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
``` ```
...@@ -148,13 +148,13 @@ Obtains the quick fix information of the application. This API uses an asynchron ...@@ -148,13 +148,13 @@ Obtains the quick fix information of the application. This API uses an asynchron
let bundleName = 'bundleName'; let bundleName = 'bundleName';
quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => { quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => {
if (error) { if (error) {
console.info(`getApplicationQuickFixInfo error: ${error}`); console.error(`getApplicationQuickFixInfo error: ${error}`);
} else { } else {
console.info(`getApplicationQuickFixInfo success: ${data}`); console.info(`getApplicationQuickFixInfo success: ${data}`);
} }
}); });
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
``` ```
...@@ -178,9 +178,9 @@ Obtains the quick fix information of the application. This API uses a promise to ...@@ -178,9 +178,9 @@ Obtains the quick fix information of the application. This API uses a promise to
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.| | Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.|
**Example** **Example**
...@@ -190,9 +190,9 @@ Obtains the quick fix information of the application. This API uses a promise to ...@@ -190,9 +190,9 @@ Obtains the quick fix information of the application. This API uses a promise to
quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => { quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => {
console.info(`getApplicationQuickFixInfo success: ${data}`); console.info(`getApplicationQuickFixInfo success: ${data}`);
}).catch((error) => { }).catch((error) => {
console.info(`getApplicationQuickFixInfo err: ${error}`); console.error(`getApplicationQuickFixInfo err: ${error}`);
}); });
} catch (paramError) { } catch (paramError) {
console.log('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
``` ```
...@@ -186,10 +186,10 @@ try { ...@@ -186,10 +186,10 @@ try {
WantAgent.getWantAgent(wantAgentInfo).then((data) => { WantAgent.getWantAgent(wantAgentInfo).then((data) => {
wantAgent = data; wantAgent = data;
}).catch((err) => { }).catch((err) => {
console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
}); });
} catch (err) { } catch (err) {
console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
``` ```
...@@ -275,12 +275,12 @@ function getWantAgentCallback(err, data) { ...@@ -275,12 +275,12 @@ function getWantAgentCallback(err, data) {
if (err === undefined) { if (err === undefined) {
wantAgent = data; wantAgent = data;
} else { } else {
console.info('getWantAgent failed ${JSON.stringify(wantAgent)}'); console.error('getWantAgent failed ${JSON.stringify(wantAgent)}');
} }
// getBundleName callback // getBundleName callback
function getBundleNameCallback(err, data) { function getBundleNameCallback(err, data) {
if(err) { if(err) {
console.info('getBundleName failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getBundleName failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} else { } else {
console.info('getBundleName ok! ${JSON.stringify(data)}'); console.info('getBundleName ok! ${JSON.stringify(data)}');
} }
...@@ -288,13 +288,13 @@ function getWantAgentCallback(err, data) { ...@@ -288,13 +288,13 @@ function getWantAgentCallback(err, data) {
try { try {
WantAgent.getBundleName(wantAgent, getBundleNameCallback); WantAgent.getBundleName(wantAgent, getBundleNameCallback);
} catch(err) { } catch(err) {
console.info('getBundleName failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getBundleName failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
} }
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) { } catch(err) {
console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
``` ```
...@@ -385,22 +385,22 @@ function getWantAgentCallback(err, data) { ...@@ -385,22 +385,22 @@ function getWantAgentCallback(err, data) {
if (err === undefined) { if (err === undefined) {
wantAgent = data; wantAgent = data;
} else { } else {
console.info('getWantAgent failed! ${JSON.stringify(wantAgent)}'); console.error('getWantAgent failed! ${JSON.stringify(wantAgent)}');
} }
try { try {
WantAgent.getBundleName(wantAgent).then((data)=>{ WantAgent.getBundleName(wantAgent).then((data)=>{
console.info('getBundleName ok! ${JSON.stringify(data)}'); console.info('getBundleName ok! ${JSON.stringify(data)}');
}).catch((err)=>{ }).catch((err)=>{
console.info('getBundleName failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getBundleName failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
}); });
} catch(err){ } catch(err){
console.info('getBundleName failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getBundleName failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
} }
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) { } catch(err) {
console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
``` ```
...@@ -492,7 +492,7 @@ function getWantAgentCallback(err, data) { ...@@ -492,7 +492,7 @@ function getWantAgentCallback(err, data) {
// getUid callback // getUid callback
function getUidCallback(err, data) { function getUidCallback(err, data) {
if(err) { if(err) {
console.info('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} else { } else {
console.info('getUid ok! ${JSON.stringify(data)}'); console.info('getUid ok! ${JSON.stringify(data)}');
} }
...@@ -500,13 +500,13 @@ function getWantAgentCallback(err, data) { ...@@ -500,13 +500,13 @@ function getWantAgentCallback(err, data) {
try { try {
WantAgent.getUid(wantAgent, getUidCallback); WantAgent.getUid(wantAgent, getUidCallback);
} catch(err) { } catch(err) {
console.info('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
} }
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) { } catch(err) {
console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
``` ```
...@@ -597,22 +597,22 @@ function getWantAgentCallback(err, data) { ...@@ -597,22 +597,22 @@ function getWantAgentCallback(err, data) {
if (err === undefined) { if (err === undefined) {
wantAgent = data; wantAgent = data;
} else { } else {
console.info('getWantAgent failed! ${JSON.stringify(wantAgent)}'); console.error('getWantAgent failed! ${JSON.stringify(wantAgent)}');
} }
try { try {
WantAgent.getUid(wantAgent).then((data)=>{ WantAgent.getUid(wantAgent).then((data)=>{
console.info('getUid ok! ${JSON.stringify(data)}'); console.info('getUid ok! ${JSON.stringify(data)}');
}).catch((err)=>{ }).catch((err)=>{
console.info('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
}); });
} catch(err){ } catch(err){
console.info('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
} }
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) { } catch(err) {
console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
``` ```
...@@ -699,12 +699,12 @@ function getWantAgentCallback(err, data) { ...@@ -699,12 +699,12 @@ function getWantAgentCallback(err, data) {
if (err === undefined) { if (err === undefined) {
wantAgent = data; wantAgent = data;
} else { } else {
console.info('getWantAgent failed ${JSON.stringify(wantAgent)}'); console.error('getWantAgent failed ${JSON.stringify(wantAgent)}');
} }
// getWant callback // getWant callback
function getWantCallback(err, data) { function getWantCallback(err, data) {
if(err) { if(err) {
console.info('getWant failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWant failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} else { } else {
console.info('getWant ok! ${JSON.stringify(data)}'); console.info('getWant ok! ${JSON.stringify(data)}');
} }
...@@ -712,13 +712,13 @@ function getWantAgentCallback(err, data) { ...@@ -712,13 +712,13 @@ function getWantAgentCallback(err, data) {
try { try {
WantAgent.getWant(wantAgent, getWantCallback); WantAgent.getWant(wantAgent, getWantCallback);
} catch(err) { } catch(err) {
console.info('getWant failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWant failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
} }
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) { } catch(err) {
console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
``` ```
...@@ -811,22 +811,22 @@ function getWantAgentCallback(err, data) { ...@@ -811,22 +811,22 @@ function getWantAgentCallback(err, data) {
if (err === undefined) { if (err === undefined) {
wantAgent = data; wantAgent = data;
} else { } else {
console.info('getWantAgent failed! ${JSON.stringify(wantAgent)}'); console.error('getWantAgent failed! ${JSON.stringify(wantAgent)}');
} }
try { try {
WantAgent.getUid(wantAgent).then((data)=>{ WantAgent.getUid(wantAgent).then((data)=>{
console.info('getUid ok! ${JSON.stringify(data)}'); console.info('getUid ok! ${JSON.stringify(data)}');
}).catch((err)=>{ }).catch((err)=>{
console.info('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
}); });
} catch(err){ } catch(err){
console.info('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
} }
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) { } catch(err) {
console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
``` ```
...@@ -912,12 +912,12 @@ function getWantAgentCallback(err, data) { ...@@ -912,12 +912,12 @@ function getWantAgentCallback(err, data) {
if (err === undefined) { if (err === undefined) {
wantAgent = data; wantAgent = data;
} else { } else {
console.info('getWantAgent failed ${JSON.stringify(wantAgent)}'); console.error('getWantAgent failed ${JSON.stringify(wantAgent)}');
} }
// cancel callback // cancel callback
function cancelCallback(err, data) { function cancelCallback(err, data) {
if(err) { if(err) {
console.info('cancel failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('cancel failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} else { } else {
console.info('cancel ok!'); console.info('cancel ok!');
} }
...@@ -925,13 +925,13 @@ function getWantAgentCallback(err, data) { ...@@ -925,13 +925,13 @@ function getWantAgentCallback(err, data) {
try { try {
WantAgent.cancel(wantAgent, cancelCallback); WantAgent.cancel(wantAgent, cancelCallback);
} catch(err) { } catch(err) {
console.info('cancel failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('cancel failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
} }
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) { } catch(err) {
console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
``` ```
...@@ -1022,22 +1022,22 @@ function getWantAgentCallback(err, data) { ...@@ -1022,22 +1022,22 @@ function getWantAgentCallback(err, data) {
if (err === undefined) { if (err === undefined) {
wantAgent = data; wantAgent = data;
} else { } else {
console.info('getWantAgent failed! ${JSON.stringify(wantAgent)}'); console.error('getWantAgent failed! ${JSON.stringify(wantAgent)}');
} }
try { try {
WantAgent.cancel(wantAgent).then((data)=>{ WantAgent.cancel(wantAgent).then((data)=>{
console.info('cancel ok!'); console.info('cancel ok!');
}).catch((err)=>{ }).catch((err)=>{
console.info('cancel failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('cancel failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
}); });
} catch(err){ } catch(err){
console.info('cancel failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('cancel failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
} }
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) { } catch(err) {
console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
``` ```
...@@ -1126,12 +1126,12 @@ function getWantAgentCallback(err, data) { ...@@ -1126,12 +1126,12 @@ function getWantAgentCallback(err, data) {
if (err === undefined) { if (err === undefined) {
wantAgent = data; wantAgent = data;
} else { } else {
console.info('getWantAgent failed ${JSON.stringify(wantAgent)}'); console.error('getWantAgent failed ${JSON.stringify(wantAgent)}');
} }
// trigger callback // trigger callback
function triggerCallback(err, data) { function triggerCallback(err, data) {
if(err) { if(err) {
console.info('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} else { } else {
console.info('getUid ok! ${JSON.stringify(data)}'); console.info('getUid ok! ${JSON.stringify(data)}');
} }
...@@ -1139,13 +1139,13 @@ function getWantAgentCallback(err, data) { ...@@ -1139,13 +1139,13 @@ function getWantAgentCallback(err, data) {
try { try {
WantAgent.trigger(wantAgent, triggerInfo, triggerCallback); WantAgent.trigger(wantAgent, triggerInfo, triggerCallback);
} catch(err) { } catch(err) {
console.info('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
} }
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) { } catch(err) {
console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
``` ```
...@@ -1234,12 +1234,12 @@ function getWantAgentCallback(err, data) { ...@@ -1234,12 +1234,12 @@ function getWantAgentCallback(err, data) {
wantAgent1 = data; wantAgent1 = data;
wantAgent2 = data; wantAgent2 = data;
} else { } else {
console.info('getWantAgent failed ${JSON.stringify(wantAgent)}'); console.error('getWantAgent failed ${JSON.stringify(wantAgent)}');
} }
// equal callback // equal callback
function equalCallback(err, data) { function equalCallback(err, data) {
if(err) { if(err) {
console.info('equal failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('equal failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} else { } else {
console.info('equal ok! ${JSON.stringify(data)}'); console.info('equal ok! ${JSON.stringify(data)}');
} }
...@@ -1247,13 +1247,13 @@ function getWantAgentCallback(err, data) { ...@@ -1247,13 +1247,13 @@ function getWantAgentCallback(err, data) {
try { try {
WantAgent.equal(wantAgent1,wantAgent2,equalCallback); WantAgent.equal(wantAgent1,wantAgent2,equalCallback);
} catch(err) { } catch(err) {
console.info('equal failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('equal failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
} }
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) { } catch(err) {
console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
``` ```
...@@ -1347,22 +1347,22 @@ function getWantAgentCallback(err, data) { ...@@ -1347,22 +1347,22 @@ function getWantAgentCallback(err, data) {
wantAgent1 = data; wantAgent1 = data;
wantAgent2 = data; wantAgent2 = data;
} else { } else {
console.info('getWantAgent failed! ${JSON.stringify(wantAgent)}'); console.error('getWantAgent failed! ${JSON.stringify(wantAgent)}');
} }
try { try {
WantAgent.equal(wantAgent1,wantAgent2).then((data)=>{ WantAgent.equal(wantAgent1,wantAgent2).then((data)=>{
console.info('equal ok! ${JSON.stringify(data)}'); console.info('equal ok! ${JSON.stringify(data)}');
}).catch((err)=>{ }).catch((err)=>{
console.info('equal failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('equal failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
}) })
} catch(err){ } catch(err){
console.info('equal failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('equal failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
} }
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) { } catch(err) {
console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
``` ```
...@@ -1446,12 +1446,12 @@ function getWantAgentCallback(err, data) { ...@@ -1446,12 +1446,12 @@ function getWantAgentCallback(err, data) {
if (err === undefined) { if (err === undefined) {
wantAgent = data; wantAgent = data;
} else { } else {
console.info('getWantAgent failed ${JSON.stringify(wantAgent)}'); console.error('getWantAgent failed ${JSON.stringify(wantAgent)}');
} }
// getOperationTypeCallback callback // getOperationTypeCallback callback
function getOperationTypeCallback(err, data) { function getOperationTypeCallback(err, data) {
if(err) { if(err) {
console.info('getOperationType failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getOperationType failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} else { } else {
console.info('getOperationType ok! ${JSON.stringify(data)}'); console.info('getOperationType ok! ${JSON.stringify(data)}');
} }
...@@ -1459,13 +1459,13 @@ function getWantAgentCallback(err, data) { ...@@ -1459,13 +1459,13 @@ function getWantAgentCallback(err, data) {
try { try {
WantAgent.getOperationTypeCallback(wantAgent, getOperationTypeCallback); WantAgent.getOperationTypeCallback(wantAgent, getOperationTypeCallback);
} catch(err) { } catch(err) {
console.info('getOperationTypeCallback failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getOperationTypeCallback failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
} }
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) { } catch(err) {
console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
``` ```
...@@ -1554,22 +1554,22 @@ function getWantAgentCallback(err, data) { ...@@ -1554,22 +1554,22 @@ function getWantAgentCallback(err, data) {
if (err === undefined) { if (err === undefined) {
wantAgent = data; wantAgent = data;
} else { } else {
console.info('getWantAgent failed! ${JSON.stringify(wantAgent)}'); console.error('getWantAgent failed! ${JSON.stringify(wantAgent)}');
} }
try { try {
WantAgent.getOperationType(wantAgent).then((data)=>{ WantAgent.getOperationType(wantAgent).then((data)=>{
console.info('getOperationType ok! ${JSON.stringify(data)}'); console.info('getOperationType ok! ${JSON.stringify(data)}');
}).catch((err)=>{ }).catch((err)=>{
console.info('getOperationType failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getOperationType failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
}); });
} catch(err){ } catch(err){
console.info('getOperationType failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getOperationType failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
} }
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) { } catch(err) {
console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); console.error('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}');
} }
``` ```
......
# @ohos.account.appAccount (App Account Management) # @ohos.account.appAccount (App Account Management)
The **appAccount** module provides APIs for adding, deleting, modifying, and querying app account information, and supports inter-app authentication and distributed data synchronization. The **appAccount** module provides APIs for adding, deleting, modifying, and querying app account information, and supports inter-app authentication and distributed data synchronization.
...@@ -1685,7 +1685,7 @@ Deletes the authorization token of the specified authentication type for an app ...@@ -1685,7 +1685,7 @@ Deletes the authorization token of the specified authentication type for an app
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app. |
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type. |
| token | string | Yes | Token to delete.| | token | string | Yes | Authorization token to delete.|
**Return value** **Return value**
...@@ -4561,8 +4561,8 @@ Enumerates the constants. ...@@ -4561,8 +4561,8 @@ Enumerates the constants.
Enumerates the result codes. Enumerates the result codes.
> **NOTE** > **NOTE**<br>
> This enum is supported since API version 8 and deprecated since API version 9. From API version 9, error codes are used. For details about the error codes, see [App Account Error Codes](../errorcodes/errorcode-app-account.md). > This enum is supported since API version 8 and deprecated since API version 9. Error codes are used from API version 9. For details, see [Account Management Error Codes](../errorcodes/errorcode-account.md).
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
...@@ -4910,9 +4910,9 @@ Checks the account labels. This API uses an asynchronous callback to return the ...@@ -4910,9 +4910,9 @@ Checks the account labels. This API uses an asynchronous callback to return the
| labels | Array&lt;string&gt; | Yes | Labels to check. | | labels | Array&lt;string&gt; | Yes | Labels to check. |
| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the check result.| | callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the check result.|
### isAccountRemovable<sup>9+</sup> ### checkAccountRemovable<sup>9+</sup>
isAccountRemovable(name: string, callback: AuthCallback): void; checkAccountRemovable(name: string, callback: AuthCallback): void;
Checks whether an app account can be deleted. This API uses an asynchronous callback to return the result. Checks whether an app account can be deleted. This API uses an asynchronous callback to return the result.
...@@ -4970,7 +4970,7 @@ Obtains the remote object of an authenticator. This API cannot be overloaded. ...@@ -4970,7 +4970,7 @@ Obtains the remote object of an authenticator. This API cannot be overloaded.
callback.onResult(account_appAccount.ResultCode.SUCCESS, result); callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
} }
isAccountRemovable(name, callback) { checkAccountRemovable(name, callback) {
var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: true}; var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: true};
callback.onResult(account_appAccount.ResultCode.SUCCESS, result); callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
} }
......
# @ohos.application.AbilityLifecycleCallback (AbilityLifecycleCallback)
The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onWindowStageCreate**, and **onWindowStageDestroy**, to receive lifecycle state changes in the application context. These callbacks can be used as an input parameter of [registerAbilityLifecycleCallback](js-apis-inner-application-applicationContext.md#applicationcontextregisterabilitylifecyclecallback).
> **NOTE**
>
> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
## Modules to Import
```ts
import AbilityLifecycleCallback from "@ohos.application.AbilityLifecycleCallback";
```
## AbilityLifecycleCallback.onAbilityCreate
onAbilityCreate(ability: Ability): void;
Called when an ability is created.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
## AbilityLifecycleCallback.onWindowStageCreate
onWindowStageCreate(ability: Ability, windowStage: window.WindowStage): void;
Called when the window stage of an ability is created.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
## AbilityLifecycleCallback.onWindowStageActive
onWindowStageActive(ability: Ability, windowStage: window.WindowStage): void;
Called when the window stage of an ability gains focus.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
## AbilityLifecycleCallback.onWindowStageInactive
onWindowStageInactive(ability: Ability, windowStage: window.WindowStage): void;
Called when the window stage of an ability loses focus.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
## AbilityLifecycleCallback.onWindowStageDestroy
onWindowStageDestroy(ability: Ability, windowStage: window.WindowStage): void;
Called when the window stage of an ability is destroyed.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
## AbilityLifecycleCallback.onAbilityDestroy
onAbilityDestroy(ability: Ability): void;
Called when an ability is destroyed.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
## AbilityLifecycleCallback.onAbilityForeground
onAbilityForeground(ability: Ability): void;
Called when an ability is switched from the background to the foreground.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
## AbilityLifecycleCallback.onAbilityBackground
onAbilityBackground(ability: Ability): void;
Called when an ability is switched from the foreground to the background.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
## AbilityLifecycleCallback.onAbilityContinue
onAbilityContinue(ability: Ability): void;
Called when an ability is continued on another device.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
**Example**
```ts
import AbilityStage from "@ohos.app.ability.AbilityStage";
var lifecycleId;
export default class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("MyAbilityStage onCreate")
let AbilityLifecycleCallback = {
onAbilityCreate(ability) {
console.log("onAbilityCreate ability:" + JSON.stringify(ability));
},
onWindowStageCreate(ability, windowStage) {
console.log("onWindowStageCreate ability:" + JSON.stringify(ability));
console.log("onWindowStageCreate windowStage:" + JSON.stringify(windowStage));
},
onWindowStageActive(ability, windowStage) {
console.log("onWindowStageActive ability:" + JSON.stringify(ability));
console.log("onWindowStageActive windowStage:" + JSON.stringify(windowStage));
},
onWindowStageInactive(ability, windowStage) {
console.log("onWindowStageInactive ability:" + JSON.stringify(ability));
console.log("onWindowStageInactive windowStage:" + JSON.stringify(windowStage));
},
onWindowStageDestroy(ability, windowStage) {
console.log("onWindowStageDestroy ability:" + JSON.stringify(ability));
console.log("onWindowStageDestroy windowStage:" + JSON.stringify(windowStage));
},
onAbilityDestroy(ability) {
console.log("onAbilityDestroy ability:" + JSON.stringify(ability));
},
onAbilityForeground(ability) {
console.log("onAbilityForeground ability:" + JSON.stringify(ability));
},
onAbilityBackground(ability) {
console.log("onAbilityBackground ability:" + JSON.stringify(ability));
},
onAbilityContinue(ability) {
console.log("onAbilityContinue ability:" + JSON.stringify(ability));
}
}
// 1. Obtain applicationContext through the context attribute.
let applicationContext = this.context.getApplicationContext();
// 2. Use applicationContext to register a listener for the ability lifecycle in the application.
lifecycleId = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback);
console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId));
}
onDestroy() {
let applicationContext = this.context.getApplicationContext();
applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => {
console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error));
});
}
}
```
...@@ -29,9 +29,12 @@ Checks whether this application is undergoing a stability test. This API uses an ...@@ -29,9 +29,12 @@ Checks whether this application is undergoing a stability test. This API uses an
**Example** **Example**
```ts ```ts
appManager.isRunningInStabilityTest((err, flag) => { appManager.isRunningInStabilityTest((error, flag) => {
console.log('error: ${JSON.stringify(err)}'); if (error && error.code !== 0) {
console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}'); console.error('isRunningInStabilityTest fail, error: ${JSON.stringify(error)}');
} else {
console.log('isRunningInStabilityTest success, the result is: ${JSON.stringify(flag)}');
}
}); });
``` ```
...@@ -56,7 +59,7 @@ Checks whether this application is undergoing a stability test. This API uses a ...@@ -56,7 +59,7 @@ Checks whether this application is undergoing a stability test. This API uses a
appManager.isRunningInStabilityTest().then((flag) => { appManager.isRunningInStabilityTest().then((flag) => {
console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}'); console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}');
}).catch((error) => { }).catch((error) => {
console.log('error: ${JSON.stringify(error)}'); console.error('error: ${JSON.stringify(error)}');
}); });
``` ```
...@@ -81,7 +84,7 @@ Checks whether this application is running on a RAM constrained device. This API ...@@ -81,7 +84,7 @@ Checks whether this application is running on a RAM constrained device. This API
appManager.isRamConstrainedDevice().then((data) => { appManager.isRamConstrainedDevice().then((data) => {
console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}'); console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}');
}).catch((error) => { }).catch((error) => {
console.log('error: ${JSON.stringify(error)}'); console.error('error: ${JSON.stringify(error)}');
}); });
``` ```
...@@ -102,9 +105,12 @@ Checks whether this application is running on a RAM constrained device. This API ...@@ -102,9 +105,12 @@ Checks whether this application is running on a RAM constrained device. This API
**Example** **Example**
```ts ```ts
appManager.isRamConstrainedDevice((err, data) => { appManager.isRamConstrainedDevice((error, data) => {
console.log('error: ${JSON.stringify(err)}'); if (error && error.code !== 0) {
console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}'); console.error('isRamConstrainedDevice fail, error: ${JSON.stringify(error)}');
} else {
console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}');
}
}); });
``` ```
...@@ -128,7 +134,7 @@ Obtains the memory size of this application. This API uses a promise to return t ...@@ -128,7 +134,7 @@ Obtains the memory size of this application. This API uses a promise to return t
appManager.getAppMemorySize().then((data) => { appManager.getAppMemorySize().then((data) => {
console.log('The size of app memory is: ${JSON.stringify(data)}'); console.log('The size of app memory is: ${JSON.stringify(data)}');
}).catch((error) => { }).catch((error) => {
console.log('error: ${JSON.stringify(error)}'); console.error('error: ${JSON.stringify(error)}');
}); });
``` ```
...@@ -149,9 +155,12 @@ Obtains the memory size of this application. This API uses an asynchronous callb ...@@ -149,9 +155,12 @@ Obtains the memory size of this application. This API uses an asynchronous callb
**Example** **Example**
```ts ```ts
appManager.getAppMemorySize((err, data) => { appManager.getAppMemorySize((error, data) => {
console.log('error: ${JSON.stringify(err)}'); if (error && error.code !== 0) {
console.log('The size of app memory is: ${JSON.stringify(data)}'); console.error('getAppMemorySize fail, error: ${JSON.stringify(error)}');
} else {
console.log('The size of app memory is: ${JSON.stringify(data)}');
}
}); });
``` ```
## appManager.getProcessRunningInfos<sup>(deprecated)</sup> ## appManager.getProcessRunningInfos<sup>(deprecated)</sup>
...@@ -178,7 +187,7 @@ Obtains information about the running processes. This API uses a promise to retu ...@@ -178,7 +187,7 @@ Obtains information about the running processes. This API uses a promise to retu
appManager.getProcessRunningInfos().then((data) => { appManager.getProcessRunningInfos().then((data) => {
console.log('The process running infos is: ${JSON.stringify(data)}'); console.log('The process running infos is: ${JSON.stringify(data)}');
}).catch((error) => { }).catch((error) => {
console.log('error: ${JSON.stringify(error)}'); console.error('error: ${JSON.stringify(error)}');
}); });
``` ```
...@@ -203,9 +212,12 @@ Obtains information about the running processes. This API uses an asynchronous c ...@@ -203,9 +212,12 @@ Obtains information about the running processes. This API uses an asynchronous c
**Example** **Example**
```ts ```ts
appManager.getProcessRunningInfos((err, data) => { appManager.getProcessRunningInfos((error, data) => {
console.log('error: ${JSON.stringify(err)}'); if (error && error.code !== 0) {
console.log('The process running infos is: ${JSON.stringify(data)}'); console.error('getProcessRunningInfos fail, error: ${JSON.stringify(error)}');
} else {
console.log('getProcessRunningInfos success, data: ${JSON.stringify(data)}');
}
}); });
``` ```
...@@ -320,7 +332,7 @@ Deregisters the application state observer. This API uses an asynchronous callba ...@@ -320,7 +332,7 @@ Deregisters the application state observer. This API uses an asynchronous callba
function unregisterApplicationStateObserverCallback(err) { function unregisterApplicationStateObserverCallback(err) {
if (err) { if (err) {
console.log('------------ unregisterApplicationStateObserverCallback ------------', err); console.error('------------ unregisterApplicationStateObserverCallback ------------', err);
} }
} }
appManager.unregisterApplicationStateObserver(observerId, unregisterApplicationStateObserverCallback); appManager.unregisterApplicationStateObserver(observerId, unregisterApplicationStateObserverCallback);
...@@ -360,7 +372,7 @@ Deregisters the application state observer. This API uses a promise to return th ...@@ -360,7 +372,7 @@ Deregisters the application state observer. This API uses a promise to return th
console.log('----------- unregisterApplicationStateObserver success ----------', data); console.log('----------- unregisterApplicationStateObserver success ----------', data);
}) })
.catch((err) => { .catch((err) => {
console.log('----------- unregisterApplicationStateObserver fail ----------', err); console.error('----------- unregisterApplicationStateObserver fail ----------', err);
}); });
``` ```
...@@ -387,7 +399,7 @@ Obtains information about the applications that are running in the foreground. T ...@@ -387,7 +399,7 @@ Obtains information about the applications that are running in the foreground. T
```ts ```ts
function getForegroundApplicationsCallback(err, data) { function getForegroundApplicationsCallback(err, data) {
if (err) { if (err) {
console.log('--------- getForegroundApplicationsCallback fail ---------', err); console.error('--------- getForegroundApplicationsCallback fail ---------', err);
} else { } else {
console.log('--------- getForegroundApplicationsCallback success ---------', data); console.log('--------- getForegroundApplicationsCallback success ---------', data);
} }
...@@ -421,7 +433,7 @@ Obtains information about the applications that are running in the foreground. T ...@@ -421,7 +433,7 @@ Obtains information about the applications that are running in the foreground. T
console.log('--------- getForegroundApplications success -------', data); console.log('--------- getForegroundApplications success -------', data);
}) })
.catch((err) => { .catch((err) => {
console.log('--------- getForegroundApplications fail -------', err); console.error('--------- getForegroundApplications fail -------', err);
}); });
``` ```
...@@ -454,7 +466,7 @@ appManager.killProcessWithAccount(bundleName, accountId) ...@@ -454,7 +466,7 @@ appManager.killProcessWithAccount(bundleName, accountId)
console.log('------------ killProcessWithAccount success ------------', data); console.log('------------ killProcessWithAccount success ------------', data);
}) })
.catch((err) => { .catch((err) => {
console.log('------------ killProcessWithAccount fail ------------', err); console.error('------------ killProcessWithAccount fail ------------', err);
}); });
``` ```
...@@ -486,7 +498,7 @@ let bundleName = 'bundleName'; ...@@ -486,7 +498,7 @@ let bundleName = 'bundleName';
let accountId = 0; let accountId = 0;
function killProcessWithAccountCallback(err, data) { function killProcessWithAccountCallback(err, data) {
if (err) { if (err) {
console.log('------------- killProcessWithAccountCallback fail, err: --------------', err); console.error('------------- killProcessWithAccountCallback fail, err: --------------', err);
} else { } else {
console.log('------------- killProcessWithAccountCallback success, data: --------------', data); console.log('------------- killProcessWithAccountCallback success, data: --------------', data);
} }
...@@ -519,7 +531,7 @@ Kills a process by bundle name. This API uses an asynchronous callback to return ...@@ -519,7 +531,7 @@ Kills a process by bundle name. This API uses an asynchronous callback to return
let bundleName = 'bundleName'; let bundleName = 'bundleName';
function killProcessesByBundleNameCallback(err, data) { function killProcessesByBundleNameCallback(err, data) {
if (err) { if (err) {
console.log('------------- killProcessesByBundleNameCallback fail, err: --------------', err); console.error('------------- killProcessesByBundleNameCallback fail, err: --------------', err);
} else { } else {
console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data); console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data);
} }
...@@ -560,7 +572,7 @@ Kills a process by bundle name. This API uses a promise to return the result. ...@@ -560,7 +572,7 @@ Kills a process by bundle name. This API uses a promise to return the result.
console.log('------------ killProcessesByBundleName success ------------', data); console.log('------------ killProcessesByBundleName success ------------', data);
}) })
.catch((err) => { .catch((err) => {
console.log('------------ killProcessesByBundleName fail ------------', err); console.error('------------ killProcessesByBundleName fail ------------', err);
}); });
``` ```
...@@ -589,7 +601,7 @@ Clears application data by bundle name. This API uses an asynchronous callback t ...@@ -589,7 +601,7 @@ Clears application data by bundle name. This API uses an asynchronous callback t
let bundleName = 'bundleName'; let bundleName = 'bundleName';
function clearUpApplicationDataCallback(err, data) { function clearUpApplicationDataCallback(err, data) {
if (err) { if (err) {
console.log('------------- clearUpApplicationDataCallback fail, err: --------------', err); console.error('------------- clearUpApplicationDataCallback fail, err: --------------', err);
} else { } else {
console.log('------------- clearUpApplicationDataCallback success, data: --------------', data); console.log('------------- clearUpApplicationDataCallback success, data: --------------', data);
} }
...@@ -630,6 +642,6 @@ Clears application data by bundle name. This API uses a promise to return the re ...@@ -630,6 +642,6 @@ Clears application data by bundle name. This API uses a promise to return the re
console.log('------------ clearUpApplicationData success ------------', data); console.log('------------ clearUpApplicationData success ------------', data);
}) })
.catch((err) => { .catch((err) => {
console.log('------------ clearUpApplicationData fail ------------', err); console.error('------------ clearUpApplicationData fail ------------', err);
}); });
``` ```
...@@ -41,10 +41,10 @@ export default class EntryAbility extends UIAbility { ...@@ -41,10 +41,10 @@ export default class EntryAbility extends UIAbility {
windowStage.loadContent('pages/index', (err, data) => { windowStage.loadContent('pages/index', (err, data) => {
if (err.code) { if (err.code) {
console.error('failed to load the content, error: + ${JSON.stringify(err)}'); console.error('failed to load the content, error: ${JSON.stringify(err)}');
return; return;
} }
console.info('Succeeded in loading the content, data: + ${JSON.stringify(data)}'); console.info('Succeeded in loading the content, data: ${JSON.stringify(data)}');
}); });
} }
} }
......
...@@ -54,7 +54,7 @@ export default class EntryAbility extends UIAbility { ...@@ -54,7 +54,7 @@ export default class EntryAbility extends UIAbility {
onCreate() { onCreate() {
console.log('MyAbility onCreate'); console.log('MyAbility onCreate');
globalThis.applicationContext = this.context.getApplicationContext(); globalThis.applicationContext = this.context.getApplicationContext();
let EnvironmentCallback = { let environmentCallback = {
onConfigurationUpdated(config){ onConfigurationUpdated(config){
console.log('onConfigurationUpdated config: ${JSON.stringify(config)}'); console.log('onConfigurationUpdated config: ${JSON.stringify(config)}');
}, },
...@@ -65,13 +65,17 @@ export default class EntryAbility extends UIAbility { ...@@ -65,13 +65,17 @@ export default class EntryAbility extends UIAbility {
// 1. Obtain an applicationContext object. // 1. Obtain an applicationContext object.
let applicationContext = globalThis.applicationContext; let applicationContext = globalThis.applicationContext;
// 2. Register a listener for the environment changes through the applicationContext object. // 2. Register a listener for the environment changes through the applicationContext object.
callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); callbackId = applicationContext.registerEnvironmentCallback(environmentCallback);
console.log('registerEnvironmentCallback number: ${JSON.stringify(callbackId)}'); console.log('registerEnvironmentCallback number: ${JSON.stringify(callbackId)}');
} }
onDestroy() { onDestroy() {
let applicationContext = globalThis.applicationContext; let applicationContext = globalThis.applicationContext;
applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => {
console.log('unregisterEnvironmentCallback success, err: ${JSON.stringify(error)}'); if (error && error.code !== 0) {
console.error('unregisterEnvironmentCallback fail, error: ${JSON.stringify(error)}');
} else {
console.log('unregisterEnvironmentCallback success, data: ${JSON.stringify(data)}');
}
}); });
} }
} }
......
# @ohos.application.errorManager (ErrorManager)
The **ErrorManager** module provides APIs for registering and deregistering error observers.
> **NOTE**
>
> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.errorManager](js-apis-app-ability-errorManager.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import errorManager from '@ohos.application.errorManager';
```
## ErrorManager.registerErrorObserver
registerErrorObserver(observer: ErrorObserver): number;
Registers an error observer.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| observer | [ErrorObserver](js-apis-inner-application-errorObserver.md) | Yes| Numeric code of the observer.|
**Example**
```ts
var observer = {
onUnhandledException(errorMsg) {
console.log('onUnhandledException, errorMsg: ', errorMsg)
}
}
errorManager.registerErrorObserver(observer)
```
## ErrorManager.unregisterErrorObserver
unregisterErrorObserver(observerId: number, callback: AsyncCallback\<void>): void;
Deregisters an error observer. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| observerId | number | Yes| Numeric code of the observer.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Example**
```ts
var observerId = 100;
function unregisterErrorObserverCallback(err) {
if (err) {
console.log('------------ unregisterErrorObserverCallback ------------', err);
}
}
errorManager.unregisterErrorObserver(observerId, unregisterErrorObserverCallback);
```
## ErrorManager.unregisterErrorObserver
unregisterErrorObserver(observerId: number): Promise\<void>;
Deregisters an error observer. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| observerId | number | Yes| Numeric code of the observer.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```ts
var observerId = 100;
errorManager.unregisterErrorObserver(observerId)
.then((data) => {
console.log('----------- unregisterErrorObserver success ----------', data);
})
.catch((err) => {
console.log('----------- unregisterErrorObserver fail ----------', err);
})
```
...@@ -404,11 +404,9 @@ arrayList.add(2); ...@@ -404,11 +404,9 @@ arrayList.add(2);
arrayList.add(4); arrayList.add(4);
arrayList.add(5); arrayList.add(5);
arrayList.add(4); arrayList.add(4);
arrayList.replaceAllElements((value: number, index: number)=> { arrayList.replaceAllElements((value) => {
return value = 2 * value; // Add the user operation logic based on the actual scenario.
}); return value;
arrayList.replaceAllElements((value: number, index: number) => {
return value = value - 2;
}); });
``` ```
...@@ -453,7 +451,7 @@ arrayList.add(4); ...@@ -453,7 +451,7 @@ arrayList.add(4);
arrayList.add(5); arrayList.add(5);
arrayList.add(4); arrayList.add(4);
arrayList.forEach((value, index) => { arrayList.forEach((value, index) => {
console.log(`value:${value}`, index); console.log("value:" + value, "index:" + index);
}); });
``` ```
...@@ -796,14 +794,14 @@ arrayList.add(4); ...@@ -796,14 +794,14 @@ arrayList.add(4);
// Method 1: // Method 1:
for (let item of arrayList) { for (let item of arrayList) {
console.log(`value:${item}`); console.log(`value:${item}`);
} }
// Method 2: // Method 2:
let iter = arrayList[Symbol.iterator](); let iter = arrayList[Symbol.iterator]();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
console.log(`value:${temp}`); console.log(`value:${temp}`);
temp = iter.next().value; temp = iter.next().value;
} }
``` ```
# PackInfo # BundlePackInfo
The **PackInfo** module provides information in the **pack.info** file. The information can be obtained using [freeInstall.getBundlePackInfo](js-apis-freeInstall.md). The **BundlePackInfo** module provides information in the **pack.info** file. The information can be obtained using [freeInstall.getBundlePackInfo](js-apis-freeInstall.md).
> **NOTE** > **NOTE**
> >
...@@ -91,7 +91,7 @@ The **PackInfo** module provides information in the **pack.info** file. The info ...@@ -91,7 +91,7 @@ The **PackInfo** module provides information in the **pack.info** file. The info
| ------- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | | ------- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ |
| name | string | Yes | No | Name of the ability. The name must be unique in the bundle. | | name | string | Yes | No | Name of the ability. The name must be unique in the bundle. |
| label | string | Yes | No | Name of the ability displayed to users. The value is a resource index to names in multiple languages.| | label | string | Yes | No | Name of the ability displayed to users. The value is a resource index to names in multiple languages.|
| visible | boolean | Yes | No | Whether the ability can be called by other bundles. The value **true** means that the ability can be called by other bundles, and **false** means the opposite.| | exported | boolean | Yes | No | Whether the ability can be called by other bundles. The value **true** means that the ability can be called by other bundles, and **false** means the opposite.|
| forms | Array\<[AbilityFormInfo](#abilityforminfo)> | Yes | No | Widget information. | | forms | Array\<[AbilityFormInfo](#abilityforminfo)> | Yes | No | Widget information. |
## ExtensionAbility ## ExtensionAbility
......
...@@ -22,7 +22,7 @@ The **AbilityInfo** module defines the ability information. A system application ...@@ -22,7 +22,7 @@ The **AbilityInfo** module defines the ability information. A system application
| icon | string | Yes | No | Index of the ability icon resource file. | | icon | string | Yes | No | Index of the ability icon resource file. |
| iconId | number | Yes | No | ID of the ability icon. | | iconId | number | Yes | No | ID of the ability icon. |
| process | string | Yes | No | Process in which the ability runs. If this parameter is not set, the bundle name is used.| | process | string | Yes | No | Process in which the ability runs. If this parameter is not set, the bundle name is used.|
| isVisible | boolean | Yes | No | Whether the ability can be called by other bundles. | | exported | boolean | Yes | No | Whether the ability can be called by other bundles. |
| type | [AbilityType](js-apis-bundleManager.md#abilitytype) | Yes | No | Ability type.<br>This attribute can be used only in the FA model.| | type | [AbilityType](js-apis-bundleManager.md#abilitytype) | Yes | No | Ability type.<br>This attribute can be used only in the FA model.|
| orientation | [DisplayOrientation](js-apis-bundleManager.md#displayorientation) | Yes | No | Ability display orientation. | | orientation | [DisplayOrientation](js-apis-bundleManager.md#displayorientation) | Yes | No | Ability display orientation. |
| launchType | [LaunchType](js-apis-bundleManager.md#launchtype) | Yes | No | Ability launch mode. | | launchType | [LaunchType](js-apis-bundleManager.md#launchtype) | Yes | No | Ability launch mode. |
......
...@@ -305,7 +305,7 @@ let hashSet = new HashSet(); ...@@ -305,7 +305,7 @@ let hashSet = new HashSet();
hashSet.add("sparrow"); hashSet.add("sparrow");
hashSet.add("squirrel"); hashSet.add("squirrel");
hashSet.forEach((value, key) => { hashSet.forEach((value, key) => {
console.log("value:" + value, key); console.log("value:" + value, "key:" + key);
}); });
``` ```
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册