提交 010e9a9c 编写于 作者: D dingxiaochen 提交者: Gitee

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

Signed-off-by: Ndingxiaochen <dingxiaochen@huawei.com>
...@@ -127,7 +127,7 @@ The following table describes the subsystems of OpenHarmony. For details about t ...@@ -127,7 +127,7 @@ The following table describes the subsystems of OpenHarmony. For details about t
| Build | Provides a compilation and building framework based on Generate Ninja (GN) and Ninja. | All systems | | Build | Provides a compilation and building framework based on Generate Ninja (GN) and Ninja. | All systems |
| Test | The test-driven development mode is used during the development process. You can develop new cases or modify existing cases to test new or enhanced system features. The test helps you develop high-quality code in the development phase.| All systems | | Test | The test-driven development mode is used during the development process. You can develop new cases or modify existing cases to test new or enhanced system features. The test helps you develop high-quality code in the development phase.| All systems |
| Data Management | Provides local data management and distributed data management:<br>- Local application data management for lightweight preference databases and relational databases<br>- Distributed data service to provide applications with the capability to store data in the databases of different devices| Standard system | | Data Management | Provides local data management and distributed data management:<br>- Local application data management for lightweight preference databases and relational databases<br>- Distributed data service to provide applications with the capability to store data in the databases of different devices| Standard system |
| Programming Language Runtime| Provides the compilation and execution environment for programs developed with JavaScript or C/C++, basic libraries that support the runtime, and the runtime-associated APIs, compilers, and auxiliary tools.| All systems | | Compiler and Runtime | Provides the compilation and execution environment for programs developed with JavaScript or C/C++, basic libraries that support the runtime, and the runtime-associated APIs, compilers, and auxiliary tools.| All systems |
| Distributed Scheduler| Starts, registers, queries, and manages system services. | All systems | | Distributed Scheduler| Starts, registers, queries, and manages system services. | All systems |
| JS UI Framework | OpenHarmony JS UI framework supports web-development-like paradigm. | All systems | | JS UI Framework | OpenHarmony JS UI framework supports web-development-like paradigm. | All systems |
| Multimedia | Provides easy-to-use APIs for developing multimedia components such as audio, video, and camera, and enables applications to use multimedia resources of the system.| All systems | | Multimedia | Provides easy-to-use APIs for developing multimedia components such as audio, video, and camera, and enables applications to use multimedia resources of the system.| All systems |
......
...@@ -17,7 +17,6 @@ ...@@ -17,7 +17,6 @@
- Application Package Structure - Application Package Structure
- [Application Package Structure in Stage Model)](quick-start/application-package-structure-stage.md) - [Application Package Structure in Stage Model)](quick-start/application-package-structure-stage.md)
- [Application Package Structure in FA Model](quick-start/application-package-structure-fa.md) - [Application Package Structure in FA Model](quick-start/application-package-structure-fa.md)
- [HAR File Structure](quick-start/har-structure.md)
- Multi-HAP Mechanism - Multi-HAP Mechanism
- [Multi-HAP Design Objectives](quick-start/multi-hap-objective.md) - [Multi-HAP Design Objectives](quick-start/multi-hap-objective.md)
- [Multi-HAP Build View](quick-start/multi-hap-build-view.md) - [Multi-HAP Build View](quick-start/multi-hap-build-view.md)
...@@ -49,7 +48,7 @@ ...@@ -49,7 +48,7 @@
- Development - Development
- [Application Models](application-models/Readme-EN.md) - [Application Models](application-models/Readme-EN.md)
- [UI Development](ui/Readme-EN.md) - [UI Development](ui/Readme-EN.md)
- [Common Event and Notification](notification/Readme-EN.md) - [Notification](notification/Readme-EN.md)
- [Window Manager](windowmanager/Readme-EN.md) - [Window Manager](windowmanager/Readme-EN.md)
- [WebGL](webgl/Readme-EN.md) - [WebGL](webgl/Readme-EN.md)
- [Media](media/Readme-EN.md) - [Media](media/Readme-EN.md)
...@@ -57,7 +56,7 @@ ...@@ -57,7 +56,7 @@
- [Connectivity](connectivity/Readme-EN.md) - [Connectivity](connectivity/Readme-EN.md)
- [Data Management](database/Readme-EN.md) - [Data Management](database/Readme-EN.md)
- [File Management](file-management/Readme-EN.md) - [File Management](file-management/Readme-EN.md)
- [Telephony](telephony/Readme-EN.md) - [Telephony Service](telephony/Readme-EN.md)
- [Task Management](task-management/Readme-EN.md) - [Task Management](task-management/Readme-EN.md)
- [Device Management](device/Readme-EN.md) - [Device Management](device/Readme-EN.md)
- [Device Usage Statistics](device-usage-statistics/Readme-EN.md) - [Device Usage Statistics](device-usage-statistics/Readme-EN.md)
......
...@@ -24,13 +24,13 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O ...@@ -24,13 +24,13 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O
All applications should be developed on top of these frameworks. All applications should be developed on top of these frameworks.
Then, equip yourself for developing the key features, with the following guidelines: Then, equip yourself for developing the key features, with the following guidelines:
- [Common Event and Notification](notification/Readme-EN.md) - [Notification](notification/Readme-EN.md)
- [Window Manager](windowmanager/Readme-EN.md) - [Window Manager](windowmanager/Readme-EN.md)
- [WebGL](webgl/Readme-EN.md) - [WebGL](webgl/Readme-EN.md)
- [Media](media/Readme-EN.md) - [Media](media/Readme-EN.md)
- [Security](security/Readme-EN.md) - [Security](security/Readme-EN.md)
- [Connectivity](connectivity/Readme-EN.md) - [Connectivity](connectivity/Readme-EN.md)
- [Telephony](telephony/Readme-EN.md) - [Telephony Service](telephony/Readme-EN.md)
- [Data Management](database/Readme-EN.md) - [Data Management](database/Readme-EN.md)
- [Task Management](task-management/Readme-EN.md) - [Task Management](task-management/Readme-EN.md)
- [Device Management](device/Readme-EN.md) - [Device Management](device/Readme-EN.md)
...@@ -40,6 +40,7 @@ Then, equip yourself for developing the key features, with the following guideli ...@@ -40,6 +40,7 @@ Then, equip yourself for developing the key features, with the following guideli
- [Application Test](application-test/Readme-EN.md) - [Application Test](application-test/Readme-EN.md)
- [IDL Specifications and User Guide](IDL/idl-guidelines.md) - [IDL Specifications and User Guide](IDL/idl-guidelines.md)
- [Using Native APIs in Application Projects](napi/Readme-EN.md) - [Using Native APIs in Application Projects](napi/Readme-EN.md)
- [File Management](file-management/medialibrary-overview.md)
### Tools ### Tools
......
...@@ -24,13 +24,13 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O ...@@ -24,13 +24,13 @@ 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-overview.md) - [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)
- [Security](security/userauth-overview.md) - [Security](security/userauth-overview.md)
- [Connectivity](connectivity/ipc-rpc-overview.md) - [Connectivity](connectivity/ipc-rpc-overview.md)
- [Telephony](telephony/telephony-overview.md) - [Telephony Service](telephony/telephony-overview.md)
- [Data Management](database/database-mdds-overview.md) - [Data Management](database/database-mdds-overview.md)
- [Task Management](task-management/background-task-overview.md) - [Task Management](task-management/background-task-overview.md)
- [Device](device/usb-overview.md) - [Device](device/usb-overview.md)
...@@ -40,6 +40,7 @@ Then, equip yourself for developing the key features, with the following guideli ...@@ -40,6 +40,7 @@ Then, equip yourself for developing the key features, with the following guideli
- [Application Test](application-test/arkxtest-guidelines.md) - [Application Test](application-test/arkxtest-guidelines.md)
- [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) - [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md)
- [Using Native APIs in Application Projects](napi/napi-guidelines.md) - [Using Native APIs in Application Projects](napi/napi-guidelines.md)
- [File Management](file-management/medialibrary-overview.md)
### Tools ### Tools
......
...@@ -17,11 +17,11 @@ ...@@ -17,11 +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 (System Applications Only)](datashareextensionability.md) - [DataShareExtensionAbility (for 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) - [AccessibilityExtensionAbility](accessibilityextensionability.md)
- [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md) - [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md)
- [InputMethodExtensionAbility](inputmethodextentionability.md)
- [WindowExtensionAbility](windowextensionability.md) - [WindowExtensionAbility](windowextensionability.md)
- [AbilityStage Component Container](abilitystage.md) - [AbilityStage Component Container](abilitystage.md)
- [Context](application-context-stage.md) - [Context](application-context-stage.md)
...@@ -35,16 +35,19 @@ ...@@ -35,16 +35,19 @@
- [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 (System Applications Only)](hop-cross-device-migration.md) - [Cross-Device Migration (for System Applications Only)](hop-cross-device-migration.md)
- [Multi-device Collaboration (System Applications Only)](hop-multi-device-collaboration.md) - [Multi-device Collaboration (for System Applications Only)](hop-multi-device-collaboration.md)
- [Subscribing to System Environment Variable Changes](subscribe-system-environment-variable-changes.md) - [Subscribing to System Environment Variable Changes](subscribe-system-environment-variable-changes.md)
- IPC - IPC
- [Process Model](process-model-stage.md) - [Process Model](process-model-stage.md)
- Common Events - Common Events
- [Introduction to Common Events](common-event-overview.md) - [Introduction to Common Events](common-event-overview.md)
- [Subscribing to Common Events](common-event-subscription.md) - Common Event Subscription
- [Publishing Common Events](common-event-publish.md) - [Common Event Subscription Overview](common-event-subscription-overview.md)
- [Subscribing to Common Events in Dynamic Mode](common-event-subscription.md)
- [Subscribing to Common Events in Static Mode (for System Applications Only)](common-event-static-subscription.md)
- [Unsubscribing from Common Events](common-event-unsubscription.md) - [Unsubscribing from Common Events](common-event-unsubscription.md)
- [Publishing Common Events](common-event-publish.md)
- [Background Services](background-services.md) - [Background Services](background-services.md)
- Inter-Thread Communication - Inter-Thread Communication
- [Thread Model](thread-model-stage.md) - [Thread Model](thread-model-stage.md)
...@@ -68,7 +71,7 @@ ...@@ -68,7 +71,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 (System Applications Only)](start-remote-pageability.md) - [Starting a Remote PageAbility (for 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)
......
...@@ -15,11 +15,11 @@ Common events are classified into system common events and custom common events. ...@@ -15,11 +15,11 @@ Common events are classified into system common events and custom common events.
Common events are also classified into unordered, ordered, and sticky common events. Common events are also classified into unordered, ordered, and sticky common events.
- Unordered common events: CES forwards common events based on the subscription sequence, regardless of whether subscribers receive the events. - Unordered common events: common events that CES forwards based on the subscription sequence, regardless of whether subscribers receive the events.
- Ordered common event: CES forwards common events to the next subscriber only after receiving a reply from the previous subscriber. - Ordered common events: common events that CES forwards based on the subscriber priority. CES forwards common events to the subscriber with lower priority only after receiving a reply from the previous subscriber with higher priority.
- Sticky common event: a public event that can be sent to a subscriber before they initiate a subscription. Only system applications or system services can send sticky common event, and they must request the **ohos.permission.COMMONEVENT_STICKY** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). - Sticky common events: common events that can be sent to a subscriber before they initiate a subscription. Only system applications and system services can send sticky common events, and they must request the **ohos.permission.COMMONEVENT_STICKY** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
Each application can subscribe to common events as required. After your application subscribes to a common event, the system sends it to your application every time the event is published. Such an event may be published by the system, other applications, or your own application. Each application can subscribe to common events as required. After your application subscribes to a common event, the system sends it to your application every time the event is published. Such an event may be published by the system, other applications, or your own application.
......
# StaticSubscriberExtensionAbility Development # Subscribing to Common Events in Static Mode (for System Applications Only)
## 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.**
## When to Use
A static subscriber is started once it receives a target event published by the system or application. At the same time, the **onReceiveEvent** callback is triggered, in which you can implement the service logic. For example, if an application needs to execute some initialization tasks during device power-on, the application can subscribe to the power-on event in static mode. After receiving the power-on event, the application is started to execute the initialization tasks. Subscribing to a common event in static mode is achieved by configuring a declaration file and implementing a class that inherits from **StaticSubscriberExtensionAbility**. Note that this subscribing mode has negative impact on system power consumption. Therefore, exercise caution when using this mode.
## How to Develop ## How to Develop
1. Prerequisites 1. Declaring a Static Subscriber
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: To declare a static subscriber, create an ExtensionAbility, which is derived from the **StaticSubscriberExtensionAbility** class, in the project. The sample code is as follows:
...@@ -38,7 +24,7 @@ ...@@ -38,7 +24,7 @@
3. Project Configuration for a Static Subscriber 2. 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: After writing the static subscriber code, configure the subscriber in the **module.json5** file. The configuration format is as follows:
...@@ -70,38 +56,50 @@ ...@@ -70,38 +56,50 @@
Pay attention to the following fields in the JSON file: 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. - **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**. - **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**. - **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.
- **name**: name of the ExtensionAbility. For a static subscriber, declare the name as **ohos.extension.staticSubscriber** for successful identification.
- **resource**: 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: A level-2 configuration file pointed to by **metadata** must be in the following format:
```ts ```ts
{ {
"commonEvents": [ "commonEvents": [
{ {
"name": "xxx", "name": "xxx",
"permission": "xxx", "permission": "xxx",
"events":[ "events":[
"xxx" "xxx"
] ]
} }
] ]
} }
``` ```
If the level-2 configuration file is not declared in this format, the file cannot be identified. The fields are described as follows: 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**. - **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. - **permission**: permission required for 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 - **events**: list of target events to subscribe to.
3. Device System Configuration
In the device system configuration file **/system/etc/app/install_list_capability.json**, add the bundle name of the static subscriber.
## Samples ```json
{
"install_list": [
{
"bundleName": "ohos.extension.staticSubscriber",
"allowCommonEvent": ["usual.event.A", "usual.event.B"],
}
]
}
```
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).
# Common Event Subscription Overview
​The common event service provides two subscription modes: dynamic and static. The biggest difference between these two modes is that dynamic subscription requires the application to be running, while static subscription does not.
- In dynamic subscription mode, a subscriber subscribes to common events by calling an API during the running period. For details, see [Subscribing to Common Events in Dynamic Mode](common-event-subscription.md).
- In static subscription mode, a subscriber subscribes to common events by configuring a declaration file and implementing a class that inherits from StaticSubscriberExtensionAbility. For details, see [Subscribing to Common Events in Static Mode](common-event-static-subscription.md).
# Subscribing to Common Events # Subscribing to Common Events in Dynamic Mode
## When to Use ## When to Use
You can create a subscriber object to subscribe to a common event so as to obtain the parameters passed in the event. Certain system common events [require specific permissions](../security/accesstoken-guidelines.md) to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEventManager.md#support). In dynamic subscription mode, an application subscribes to a common event when it is running. If the subscribed event is published during the running period, the subscriber application will receive the event, together with the parameters passed in the event. For example, if an application expects to be notified of low battery so that it can reduce power consumption accordingly when running, then the application can subscribe to the low-battery event. Upon receiving the event, the application can close some unnecessary tasks to reduce power consumption. Certain system common events [require specific permissions](../security/accesstoken-guidelines.md) to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEventManager.md#support).
## Available APIs ## Available APIs
......
# Unsubscribing from Common Events # Unsubscribing from Common Events in Dynamic Mode
## When to Use ## When to Use
You can call [unsubscribe()](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerunsubscribe) to unsubscribe from a common event that is no longer required. You can call [unsubscribe()](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerunsubscribe) to unsubscribe from a common event that is no longer required in dynamic mode.
## Available APIs ## Available APIs
...@@ -21,12 +21,12 @@ You can call [unsubscribe()](../reference/apis/js-apis-commonEventManager.md#com ...@@ -21,12 +21,12 @@ You can call [unsubscribe()](../reference/apis/js-apis-commonEventManager.md#com
import commonEventManager from '@ohos.commonEventManager'; import commonEventManager from '@ohos.commonEventManager';
``` ```
2. Subscribe to an event by following the procedure described in [Subscribing to Common Events](common-event-subscription.md). 2. Subscribe to an event by following the procedure described in [Subscribing to Common Events in Dynamic Mode](common-event-subscription.md).
3. Call **unsubscribe** in **CommonEvent** to unsubscribe from the common event. 3. Call **unsubscribe** in **CommonEvent** to unsubscribe from the common event.
```ts ```ts
// The subscriber object iscreated during event subscription. // The subscriber object is created during event subscription.
if (subscriber !== null) { if (subscriber !== null) {
commonEventManager.unsubscribe(subscriber, (err) => { commonEventManager.unsubscribe(subscriber, (err) => {
if (err) { if (err) {
......
# DataShareExtensionAbility (System Applications Only) # DataShareExtensionAbility (for System Applications Only)
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). 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 # EnterpriseAdminExtensionAbility Development
## Introduction ## Introduction to EnterpriseAdminExtensionAbility
**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. EnterpriseAdminExtensionAbility is a mandatory component for Mobile Device Management (MDM) applications. When developing MDM applications for enterprises, you need to inherit EnterpriseAdminExtensionAbility and implement MDM service logic in the EnterpriseAdminExtensionAbility instance. EnterpriseAdminExtensionAbility implements notifications of system management status changes and defines the callbacks for when a device administrator application is enabled or disabled or an application is installed or uninstalled.
## Constraints ## Constraints
- ***Function constraints*** - **Function constraints**
The APIs provided can be used only by device administrator applications. EnterpriseAdminExtensionAbility is applicable only to enterprise administrator applications.
## Scenarios: Listening for the Enable, Disable, Install, and Uninstall Events of a Device Administrator Application ## Observing Activation/Deactivation of a Device Administrator Application and Installation/Removal of an Application
### Overview ### 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. **onAdminEnabled**: When an enterprise administrator or employee deploys an MDM application and activates the device administrator application, this callback is invoked to notify the MDM application that the DeviceAdmin permission is activated. The initialization policy of the MDM application can set in **onAdminEnabled**.
**onAdminDisabled**: called when the system or employee disables the DeviceAdmin permission to notify the enterprise administrator that the device is no longer managed. **onAdminDisabled**: When the device administrator application is deactivated, the callback is invoked to notify the MDM application that the DeviceAdmin permission is deactivated.
**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. **onBundleAdded**: The enterprise administrator can subscribe to application installation and uninstallation events. When an application is installed on an enterprise device, the MDM application reports the event in this callback to notify the enterprise administrator.
**onBundleRemoved**: called to notify the enterprise administrator that the specified MDM application is uninstalled on the device. **onBundleRemoved**: When an application is removed from an enterprise device, the MDM application reports the event in this callback to notify the enterprise administrator.
### Available APIs ### Available APIs
| Class | API | Description | | Class | API | Description |
| :------------------------------ | ----------------------------------------- | ---------------------------- | | :------------------------------ | ----------------------------------------- | ---------------------------- |
| EnterpriseAdminExtensionAbility | onAdminDisabled(): void | Called when the device administrator application is enabled.| | EnterpriseAdminExtensionAbility | onAdminDisabled(): void | Called when a device administrator application is deactivated.|
| EnterpriseAdminExtensionAbility | onBundleAdded(bundleName: string): void | Called when the MDM application is installed. | | EnterpriseAdminExtensionAbility | onBundleAdded(bundleName: string): void | Called when an application is installed on a device. |
| EnterpriseAdminExtensionAbility | onAdminEnabled(): void | Called when the device administrator application is disabled. | | EnterpriseAdminExtensionAbility | onAdminEnabled(): void | Called when a device administrator application is activated. |
| EnterpriseAdminExtensionAbility | onBundleRemoved(bundleName: string): void | Called when the MDM application is uninstalled. | | EnterpriseAdminExtensionAbility | onBundleRemoved(bundleName: string): void | Called when an application is removed from a device. |
### How to Develop ### 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: To implement EnterpriseAdminExtensionAbility, you need to activate the device administrator application and create **ExtensionAbility** in 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**. 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**. 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. 3. Open the **EnterpriseExtAbility.ts** file and import the **EnterpriseAdminExtensionAbility** module. Inherit the **EnterpriseAdminExtensionAbility** module to the custom class and add application notification callbacks, such as **onAdminEnabled()** and **onAdminDisabled()**. When the device administrator application is activated or deactivated, the device administrator can receive notifications.
```ts ```ts
import EnterpriseAdminExtensionAbility from '@ohos.enterprise.EnterpriseAdminExtensionAbility'; import EnterpriseAdminExtensionAbility from '@ohos.enterprise.EnterpriseAdminExtensionAbility';
export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility { export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility {
onAdminEnabled() { onAdminEnabled() {
console.info("onAdminEnabled"); console.info("onAdminEnabled");
} }
onAdminDisabled() { onAdminDisabled() {
console.info("onAdminDisabled"); console.info("onAdminDisabled");
} }
...@@ -56,14 +56,14 @@ To implement **EnterpriseAdminExtensionAbility**, enable the device administrato ...@@ -56,14 +56,14 @@ To implement **EnterpriseAdminExtensionAbility**, enable the device administrato
onBundleAdded(bundleName: string) { onBundleAdded(bundleName: string) {
console.info("EnterpriseAdminAbility onBundleAdded bundleName:" + bundleName) console.info("EnterpriseAdminAbility onBundleAdded bundleName:" + bundleName)
} }
onBundleRemoved(bundleName: string) { onBundleRemoved(bundleName: string) {
console.info("EnterpriseAdminAbility onBundleRemoved bundleName" + bundleName) 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. 4. Register **ServiceExtensionAbility** in the [**module.json5**](../quick-start/module-configuration-file.md) file corresponding to the project module. Set **type** to **enterpriseAdmin** and **srcEntrance** to the path of the ExtensionAbility code.
```ts ```ts
"extensionAbilities": [ "extensionAbilities": [
...@@ -78,7 +78,7 @@ To implement **EnterpriseAdminExtensionAbility**, enable the device administrato ...@@ -78,7 +78,7 @@ To implement **EnterpriseAdminExtensionAbility**, enable the device administrato
## Example ## 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. Use **subscribeManagedEvent()** and **unsubscribeManagedEvent()** in the **@ohos.enterprise.adminManager** module to subscribe to application installation and removal events. When an application is installed or removed, the MDM application is notified of the event. Then, the MDM application reports the event in the callback to notify the enterprise administrator.
```ts ```ts
@State managedEvents: Array<adminManager.ManagedEvent> = [0,1] @State managedEvents: Array<adminManager.ManagedEvent> = [0,1]
...@@ -108,4 +108,3 @@ Use the **subscribeManagedEvent** and **unsubscribeManagedEvent** APIs in the ** ...@@ -108,4 +108,3 @@ Use the **subscribeManagedEvent** and **unsubscribeManagedEvent** APIs in the **
} }
``` ```
# Cross-Device Migration (System Applications Only)] # Cross-Device Migration (for System Applications Only)]
## When to Use ## When to Use
......
# Multi-device Collaboration (System Applications Only) # Multi-device Collaboration (for System Applications Only)
## When to Use ## When to Use
...@@ -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 (System Applications Only)](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction-system-applications-only). 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 (for System Applications Only)](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction-for-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.
...@@ -319,10 +319,10 @@ The following describes how to implement multi-device collaboration through cros ...@@ -319,10 +319,10 @@ The following describes how to implement multi-device collaboration through cros
| startAbilityByCall(want: Want): Promise&lt;Caller&gt;; | Starts a UIAbility in the foreground or background and obtains the caller object for communicating with the UIAbility.| | startAbilityByCall(want: Want): Promise&lt;Caller&gt;; | Starts a UIAbility in the foreground or background and obtains the caller object for communicating with the UIAbility.|
| on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.| | on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.|
| off(method: string): void | Callback invoked when the callee ability deregisters a method.| | off(method: string): void | Callback invoked when the callee ability deregisters a method.|
| call(method: string, data: rpc.Sequenceable): Promise&lt;void&gt; | Sends agreed sequenceable data to the callee ability.| | call(method: string, data: rpc.Parcelable): Promise&lt;void&gt; | Sends agreed parcelable data to the callee ability.|
| callWithResult(method: string, data: rpc.Sequenceable): Promise&lt;rpc.MessageParcel&gt; | Sends agreed sequenceable data to the callee ability and obtains the agreed sequenceable data returned by the callee ability.| | callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageSequence&gt;| Sends agreed parcelable data to the callee ability and obtains the agreed parcelable data returned by the callee ability.|
| release(): void | Releases the caller object.| | release(): void | Releases the caller object.|
| on(type:&nbsp;"release",&nbsp;callback:&nbsp;OnReleaseCallback):&nbsp;void | Callback invoked when the caller object is released.| | on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.|
### How to Develop ### How to Develop
...@@ -348,16 +348,15 @@ The following describes how to implement multi-device collaboration through cros ...@@ -348,16 +348,15 @@ The following describes how to implement multi-device collaboration through cros
For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener. For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener.
1. Configure the launch type of the UIAbility. 1. Configure the launch type of the UIAbility.
Set **launchType** of the callee ability to **singleton** in the **module.json5** file.
Set **launchType** of the callee ability to **singleton** in the **module.json5** file. | JSON Field| Description|
| -------- | -------- |
| "launchType"| Ability launch type. Set this parameter to **singleton**.|
| JSON Field| Description| An example of the UIAbility configuration is as follows:
| -------- | -------- |
| "launchType"| Ability launch type. Set this parameter to **singleton**.|
An example of the UIAbility configuration is as follows:
```json ```json
"abilities":[{ "abilities":[{
"name": ".CalleeAbility", "name": ".CalleeAbility",
...@@ -369,19 +368,18 @@ The following describes how to implement multi-device collaboration through cros ...@@ -369,19 +368,18 @@ The following describes how to implement multi-device collaboration through cros
"visible": true "visible": true
}] }]
``` ```
2. Import the **UIAbility** module. 2. Import the **UIAbility** module.
```ts ```ts
import Ability from '@ohos.app.ability.UIAbility'; import Ability from '@ohos.app.ability.UIAbility';
``` ```
3. Define the agreed parcelable data.
3. Define the agreed sequenceable data.
The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string.
The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string.
```ts ```ts
export default class MySequenceable { export default class MyParcelable {
num: number = 0; num: number = 0;
str: string = ""; str: string = "";
...@@ -390,71 +388,69 @@ The following describes how to implement multi-device collaboration through cros ...@@ -390,71 +388,69 @@ The following describes how to implement multi-device collaboration through cros
this.str = string; this.str = string;
} }
marshalling(messageParcel) { marshalling(messageSequence) {
messageParcel.writeInt(this.num); messageSequence.writeInt(this.num);
messageParcel.writeString(this.str); messageSequence.writeString(this.str);
return true; return true;
} }
unmarshalling(messageParcel) { unmarshalling(messageSequence) {
this.num = messageParcel.readInt(); this.num = messageSequence.readInt();
this.str = messageParcel.readString(); this.str = messageSequence.readString();
return true; return true;
} }
} }
``` ```
4. Implement **Callee.on** and **Callee.off**. 4. Implement **Callee.on** and **Callee.off**.
In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements.
```ts
const TAG: string = '[CalleeAbility]';
const MSG_SEND_METHOD: string = 'CallSendMsg';
function sendMsgCallback(data) {
console.info('CalleeSortFunc called');
// Obtain the sequenceable data sent by the caller ability.
let receivedData = new MySequenceable(0, '');
data.readSequenceable(receivedData);
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`);
// Process the data.
// Return the sequenceable data result to the caller ability.
return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`);
}
export default class CalleeAbility extends Ability {
onCreate(want, launchParam) {
try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback);
} catch (error) {
console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`);
}
}
onDestroy() { ```ts
try { const TAG: string = '[CalleeAbility]';
this.callee.off(MSG_SEND_METHOD); const MSG_SEND_METHOD: string = 'CallSendMsg';
} catch (error) {
console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`); function sendMsgCallback(data) {
} console.info('CalleeSortFunc called');
}
} // Obtain the parcelable data sent by the caller ability.
``` let receivedData = new MyParcelable(0, '');
data.readParcelable(receivedData);
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`);
// Process the data.
// Return the parcelable data result to the caller ability.
return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`);
}
export default class CalleeAbility extends Ability {
onCreate(want, launchParam) {
try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback);
} catch (error) {
console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`);
}
}
onDestroy() {
try {
this.callee.off(MSG_SEND_METHOD);
} catch (error) {
console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`);
}
}
}
```
4. Obtain the caller object and access the callee ability. 4. Obtain the caller object and access the callee ability.
1. Import the **UIAbility** module. 1. Import the **UIAbility** module.
```ts ```ts
import Ability from '@ohos.app.ability.UIAbility'; import Ability from '@ohos.app.ability.UIAbility';
``` ```
2. Obtain the caller object. 2. Obtain the caller object.
The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements.
```ts ```ts
async onButtonGetRemoteCaller() { async onButtonGetRemoteCaller() {
...@@ -483,14 +479,14 @@ The following describes how to implement multi-device collaboration through cros ...@@ -483,14 +479,14 @@ The following describes how to implement multi-device collaboration through cros
For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned). For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned).
5. Sends agreed sequenceable data to the callee ability. 5. Sends agreed parcelable data to the callee ability.
1. The sequenceable data can be sent to the callee ability with or without a return value. The method and sequenceable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability. 1. The parcelable data can be sent to the callee ability with or without a return value. The method and parcelable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability.
```ts ```ts
const MSG_SEND_METHOD: string = 'CallSendMsg'; const MSG_SEND_METHOD: string = 'CallSendMsg';
async onButtonCall() { async onButtonCall() {
try { try {
let msg = new MySequenceable(1, 'origin_Msg'); let msg = new MyParcelable(1, 'origin_Msg');
await this.caller.call(MSG_SEND_METHOD, msg); await this.caller.call(MSG_SEND_METHOD, msg);
} catch (error) { } catch (error) {
console.info(`caller call failed with ${error}`); console.info(`caller call failed with ${error}`);
...@@ -505,12 +501,12 @@ The following describes how to implement multi-device collaboration through cros ...@@ -505,12 +501,12 @@ The following describes how to implement multi-device collaboration through cros
backMsg: string = ''; backMsg: string = '';
async onButtonCallWithResult(originMsg, backMsg) { async onButtonCallWithResult(originMsg, backMsg) {
try { try {
let msg = new MySequenceable(1, originMsg); let msg = new MyParcelable(1, originMsg);
const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg); const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg);
console.info('caller callWithResult succeed'); console.info('caller callWithResult succeed');
let result = new MySequenceable(0, ''); let result = new MyParcelable(0, '');
data.readSequenceable(result); data.readParcelable(result);
backMsg(result.str); backMsg(result.str);
console.info(`caller result is [${result.num}, ${result.str}]`); console.info(`caller result is [${result.num}, ${result.str}]`);
} catch (error) { } catch (error) {
...@@ -521,8 +517,8 @@ The following describes how to implement multi-device collaboration through cros ...@@ -521,8 +517,8 @@ The following describes how to implement multi-device collaboration through cros
6. Release the caller object. 6. Release the caller object.
When the caller object is no longer required, use **release()** to release it. When the caller object is no longer required, use **release()** to release it.
```ts ```ts
releaseCall() { releaseCall() {
try { try {
......
...@@ -12,10 +12,10 @@ You can also use [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-i ...@@ -12,10 +12,10 @@ You can also use [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-i
This document describes the following operations: This document describes the following operations:
- [Setting a Mission Snapshot Icon (System Applications Only)](#setting-a-mission-snapshot-icon-system-applications-only) - [Setting a Mission Snapshot Icon (for System Applications Only)](#setting-a-mission-snapshot-icon-for-system-applications-only)
- [Setting a Mission Snapshot Name](#setting-a-mission-snapshot-name) - [Setting a Mission Snapshot Name](#setting-a-mission-snapshot-name)
## Setting a Mission Snapshot Icon (System Applications Only) ## Setting a Mission Snapshot Icon (for System Applications Only)
Call [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionicon) to set the icon of a mission snapshot. The icon is an object of the [PixelMap](../reference/apis/js-apis-image.md#pixelmap7) type. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). Call [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionicon) to set the icon of a mission snapshot. The icon is an object of the [PixelMap](../reference/apis/js-apis-image.md#pixelmap7) type. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts ```ts
......
...@@ -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 (System Applications Only)](#implementing-a-background-service-system-applications-only) - [Implementing a Background Service (for System Applications Only)](#implementing-a-background-service-for-system-applications-only)
- [Starting a Background Service (System Applications Only)](#starting-a-background-service-system-applications-only) - [Starting a Background Service (for System Applications Only)](#starting-a-background-service-for-system-applications-only)
- [Connecting to a Background Service](#connecting-to-a-background-service) - [Connecting to a Background Service](#connecting-to-a-background-service)
...@@ -33,7 +33,7 @@ This topic describes how to use ServiceExtensionAbility in the following scenari ...@@ -33,7 +33,7 @@ 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 (System Applications Only) ## Implementing a Background Service (for System Applications Only)
[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.
...@@ -164,7 +164,7 @@ To implement a background service, manually create a ServiceExtensionAbility com ...@@ -164,7 +164,7 @@ To implement a background service, manually create a ServiceExtensionAbility com
``` ```
## Starting a Background Service (System Applications Only) ## Starting a Background Service (for System Applications Only)
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.
......
# Starting a Remote PageAbility (System Applications Only) # Starting a Remote PageAbility (for System Applications Only)
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.
......
...@@ -15,11 +15,11 @@ This topic describes the UIAbility interaction modes in the following scenarios. ...@@ -15,11 +15,11 @@ This topic describes the UIAbility interaction modes in the following scenarios.
- [Starting UIAbility of Another Application and Obtaining the Return Result](#starting-uiability-of-another-application-and-obtaining-the-return-result) - [Starting UIAbility of Another Application and Obtaining the Return Result](#starting-uiability-of-another-application-and-obtaining-the-return-result)
- [Starting UIAbility with Window Mode Specified (System Applications Only)](#starting-uiability-with-window-mode-specified-system-applications-only) - [Starting UIAbility with Window Mode Specified (for System Applications Only)](#starting-uiability-with-window-mode-specified-for-system-applications-only)
- [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 (System Applications Only)](#using-ability-call-to-implement-uiability-interaction-system-applications-only) - [Using Ability Call to Implement UIAbility Interaction (for System Applications Only)](#using-ability-call-to-implement-uiability-interaction-for-system-applications-only)
## Starting UIAbility in the Same Application ## Starting UIAbility in the Same Application
...@@ -308,7 +308,7 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -308,7 +308,7 @@ If you want to obtain the return result when using implicit Want to start the UI
}) })
``` ```
## Starting UIAbility with Window Mode Specified (System Applications Only) ## Starting UIAbility with Window Mode Specified (for System Applications Only)
By specifying the window mode when starting the UIAbility of an application, the application can be displayed in different window modes, which can be full-screen, floating window, or split-screen. By specifying the window mode when starting the UIAbility of an application, the application can be displayed in different window modes, which can be full-screen, floating window, or split-screen.
...@@ -472,7 +472,7 @@ In summary, when a UIAbility instance of application A has been created and the ...@@ -472,7 +472,7 @@ 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 (System Applications Only) ## Using Ability Call to Implement UIAbility Interaction (for System Applications Only)
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.
...@@ -488,7 +488,7 @@ Ability call is usually used in the following scenarios: ...@@ -488,7 +488,7 @@ Ability call is usually used in the following scenarios:
- Starting the callee ability in the background - Starting the callee ability in the background
**Table 1** Terms used in the ability call **Table 1** Terms used in the ability call
| **Term**| Description| | **Term**| Description|
| -------- | -------- | | -------- | -------- |
...@@ -519,15 +519,15 @@ The following figure shows the ability call process. ...@@ -519,15 +519,15 @@ The following figure shows the ability call process.
The following table describes the main APIs used for the ability call. For details, see [AbilityContext](../reference/apis/js-apis-app-ability-uiAbility.md#caller). The following table describes the main APIs used for the ability call. For details, see [AbilityContext](../reference/apis/js-apis-app-ability-uiAbility.md#caller).
**Table 2** Ability call APIs **Table 2** Ability call APIs
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
| startAbilityByCall(want: Want): Promise&lt;Caller&gt; | Starts a UIAbility in the foreground (through the **want** configuration) or background (default) and obtains the caller object for communication with the UIAbility. For details, see [AbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartabilitybycall).| | startAbilityByCall(want: Want): Promise&lt;Caller&gt; | Starts a UIAbility in the foreground (through the **want** configuration) or background (default) and obtains the caller object for communication with the UIAbility. For details, see [AbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartabilitybycall).|
| on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.| | on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.|
| off(method: string): void | Callback invoked when the callee ability deregisters a method.| | off(method: string): void | Callback invoked when the callee ability deregisters a method.|
| call(method: string, data: rpc.Sequenceable): Promise&lt;void&gt; | Sends agreed sequenceable data to the callee ability.| | call(method: string, data: rpc.Parcelable): Promise&lt;void&gt; | Sends agreed parcelable data to the callee ability.|
| callWithResult(method: string, data: rpc.Sequenceable): Promise&lt;rpc.MessageParcel&gt; | Sends agreed sequenceable data to the callee ability and obtains the agreed sequenceable data returned by the callee ability.| | callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageSequence&gt; | Sends agreed parcelable data to the callee ability and obtains the agreed parcelable data returned by the callee ability.|
| release(): void | Releases the caller object.| | release(): void | Releases the caller object.|
| on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.| | on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.|
...@@ -571,13 +571,13 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -571,13 +571,13 @@ For the callee ability, implement the callback to receive data and the methods t
import Ability from '@ohos.app.ability.UIAbility'; import Ability from '@ohos.app.ability.UIAbility';
``` ```
3. Define the agreed sequenceable data. 3. Define the agreed parcelable data.
The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string.
```ts ```ts
export default class MySequenceable { export default class MyParcelable {
num: number = 0 num: number = 0
str: string = "" str: string = ""
...@@ -586,15 +586,15 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -586,15 +586,15 @@ For the callee ability, implement the callback to receive data and the methods t
this.str = string this.str = string
} }
marshalling(messageParcel) { marshalling(messageSequence) {
messageParcel.writeInt(this.num) messageSequence.writeInt(this.num)
messageParcel.writeString(this.str) messageSequence.writeString(this.str)
return true return true
} }
unmarshalling(messageParcel) { unmarshalling(messageSequence) {
this.num = messageParcel.readInt() this.num = messageSequence.readInt()
this.str = messageParcel.readString() this.str = messageSequence.readString()
return true return true
} }
} }
...@@ -602,7 +602,7 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -602,7 +602,7 @@ For the callee ability, implement the callback to receive data and the methods t
4. Implement **Callee.on** and **Callee.off**. 4. Implement **Callee.on** and **Callee.off**.
The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows: The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows:
```ts ```ts
const TAG: string = '[CalleeAbility]'; const TAG: string = '[CalleeAbility]';
const MSG_SEND_METHOD: string = 'CallSendMsg'; const MSG_SEND_METHOD: string = 'CallSendMsg';
...@@ -610,14 +610,14 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -610,14 +610,14 @@ For the callee ability, implement the callback to receive data and the methods t
function sendMsgCallback(data) { function sendMsgCallback(data) {
console.info('CalleeSortFunc called'); console.info('CalleeSortFunc called');
// Obtain the sequenceable data sent by the caller ability. // Obtain the parcelable data sent by the caller ability.
let receivedData = new MySequenceable(0, ''); let receivedData = new MyParcelable(0, '');
data.readSequenceable(receivedData); data.readParcelable(receivedData);
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`);
// Process the data. // Process the data.
// Return the sequenceable data result to the caller ability. // Return the parcelable data result to the caller ability.
return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`); return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`);
} }
export default class CalleeAbility extends Ability { export default class CalleeAbility extends Ability {
......
...@@ -14,7 +14,7 @@ the context is [WindowExtensionContext](../reference/apis/js-apis-inner-applicat ...@@ -14,7 +14,7 @@ the context is [WindowExtensionContext](../reference/apis/js-apis-inner-applicat
> >
## Setting an Embedded Ability (System Applications Only) ## Setting an Embedded Ability (for System Applications Only)
The **WindowExtensionAbility** class provides **onConnect()**, **onDisconnect()**, and **onWindowReady()** lifecycle callbacks, which can be overridden. The **WindowExtensionAbility** class provides **onConnect()**, **onDisconnect()**, and **onWindowReady()** lifecycle callbacks, which can be overridden.
...@@ -78,7 +78,7 @@ To implement an embedded application, manually create a WindowExtensionAbility i ...@@ -78,7 +78,7 @@ To implement an embedded application, manually create a WindowExtensionAbility i
``` ```
## Starting an Embedded Ability (System Applications Only) ## Starting an Embedded Ability (for System Applications Only)
System applications can load the created WindowExtensionAbility through the AbilityComponent. System applications can load the created WindowExtensionAbility through the AbilityComponent.
......
# HTTP Data Request # HTTP Data Request
## Use Cases ## When to Use
An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
...@@ -14,40 +14,49 @@ For details about how to apply for permissions, see [Access Control Development] ...@@ -14,40 +14,49 @@ For details about how to apply for permissions, see [Access Control Development]
The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md). The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md).
| API | Description | | API | Description |
| ----------------------------------------- | --------------------------------------------------------- | | ----------------------------------------- | ----------------------------------- |
| createHttp() | Creates an HTTP request. | | createHttp() | Creates an HTTP request. |
| request() | Initiates an HTTP request to a given URL. | | request() | Initiates an HTTP request to a given URL. |
| destroy() | Destroys an HTTP request. | | request2()<sup>10+</sup> | Initiates an HTTP network request based on the URL and returns a streaming response.|
| destroy() | Destroys an HTTP request. |
| on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. | | on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. |
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events. | | off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.|
| once\('headersReceive'\)<sup>8+</sup> | Registers a one-time observer for HTTP Response Header events.|
| on\('dataReceive'\)<sup>10+</sup> | Registers an observer for events indicating receiving of HTTP streaming responses. |
| off\('dataReceive'\)<sup>10+</sup> | Unregisters the observer for events indicating receiving of HTTP streaming responses. |
| on\('dataEnd'\)<sup>10+</sup> | Registers an observer for events indicating completion of receiving HTTP streaming responses. |
| off\('dataEnd'\)<sup>10+</sup> | Unregisters the observer for events indicating completion of receiving HTTP streaming responses.|
| on\('dataProgress'\)<sup>10+</sup> | Registers an observer for events indicating progress of receiving HTTP streaming responses. |
| off\('dataProgress'\)<sup>10+</sup> | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.|
## How to Develop ## How to Develop
1. Import the required HTTP module. 1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Create an **HttpRequest** object. 2. Call **createHttp()** to create an **HttpRequest** object.
3. (Optional) Listen for HTTP Response Header events. 3. Call **httpRequest.on()** to subscribe to HTTP response header events. This API returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements.
4. Initiate an HTTP request to a given URL. 4. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
5. (Optional) Process the HTTP Response Header event and the return result of the HTTP request. 5. Parse the returned result based on service requirements.
6. Call **off()** to unsubscribe from HTTP response header events.
7. Call **httpRequest.destroy()** to release resources after the request is processed.
```js ```js
// Import the http namespace.
import http from '@ohos.net.http'; import http from '@ohos.net.http';
// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused. // Each httpRequest corresponds to an HTTP request task and cannot be reused.
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
// This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events.
// Subscribe to the HTTP response header, which is returned earlier than HttpRequest. You can subscribe to HTTP Response Header events based on service requirements. // on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+
httpRequest.on('headersReceive', (header) => { httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
}); });
httpRequest.request( httpRequest.request(
// Set the URL of the HTTP request. You need to define the URL. Set the parameters of the request in extraData. // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL", "EXAMPLE_URL",
{ {
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add the header field based on service requirements. // You can add header fields based on service requirements.
header: { header: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
...@@ -55,21 +64,33 @@ httpRequest.request( ...@@ -55,21 +64,33 @@ httpRequest.request(
extraData: { extraData: {
"data": "data to send", "data": "data to send",
}, },
connectTimeout: 60000, // Optional. The default value is 60000, in ms. expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
usingCache: true, // Optional. The default value is true.
priority: 1, // Optional. The default value is 1.
connectTimeout: 60000 // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms. readTimeout: 60000, // Optional. The default value is 60000, in ms.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10.
}, (err, data) => { }, (err, data) => {
if (!err) { if (!err) {
// data.result contains the HTTP response. Parse the response based on service requirements. // data.result carries the HTTP response. Parse the response based on service requirements.
console.info('Result:' + data.result); console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + data.responseCode); console.info('code:' + JSON.stringify(data.responseCode));
// data.header contains the HTTP response header. Parse the content based on service requirements. // data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header)); console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+ console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else { } else {
console.info('error:' + JSON.stringify(err)); console.info('error:' + JSON.stringify(err));
// Call the destroy() method to destroy the request if it is no longer needed. // Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy(); httpRequest.destroy();
} }
} }
); );
``` ```
## Samples
The following sample is provided to help you better understand how to develop the HTTP data request feature:
- [`HTTP`: Data Request (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http)
- [HTTP Communication (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH)
...@@ -49,6 +49,7 @@ TLS Socket connection functions are mainly provided by the **tls_socket** module ...@@ -49,6 +49,7 @@ TLS Socket connection functions are mainly provided by the **tls_socket** module
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
| constructTLSSocketInstance() | Creates a **TLSSocket** object.|
| bind() | Binds the IP address and port number.| | bind() | Binds the IP address and port number.|
| close(type:&nbsp;'error') | Closes a Socket connection.| | close(type:&nbsp;'error') | Closes a Socket connection.|
| connect() | Sets up a connection to the specified IP address and port number.| | connect() | Sets up a connection to the specified IP address and port number.|
...@@ -189,7 +190,7 @@ TLS Socket connection process on the client: ...@@ -189,7 +190,7 @@ TLS Socket connection process on the client:
let tlsTwoWay = socket.constructTLSSocketInstance(); let tlsTwoWay = socket.constructTLSSocketInstance();
// Subscribe to TLS Socket connection events. // Subscribe to TLS Socket connection events.
tcp.on('message', value => { tlsTwoWay.on('message', value => {
console.log("on message") console.log("on message")
let buffer = value.message let buffer = value.message
let dataView = new DataView(buffer) let dataView = new DataView(buffer)
...@@ -199,10 +200,10 @@ TLS Socket connection process on the client: ...@@ -199,10 +200,10 @@ TLS Socket connection process on the client:
} }
console.log("on connect received:" + str) console.log("on connect received:" + str)
}); });
tcp.on('connect', () => { tlsTwoWay.on('connect', () => {
console.log("on connect") console.log("on connect")
}); });
tcp.on('close', () => { tlsTwoWay.on('close', () => {
console.log("on close") console.log("on close")
}); });
...@@ -245,23 +246,23 @@ TLS Socket connection process on the client: ...@@ -245,23 +246,23 @@ TLS Socket connection process on the client:
console.log(data); console.log(data);
}); });
// Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events. // Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tls.close((err) => { tlsTwoWay.close((err) => {
if (err) { if (err) {
console.log("close callback error = " + err); console.log("close callback error = " + err);
} else { } else {
console.log("close success"); console.log("close success");
} }
tls.off('message'); tlsTwoWay.off('message');
tls.off('connect'); tlsTwoWay.off('connect');
tls.off('close'); tlsTwoWay.off('close');
}); });
// Create a TLS Socket connection (for one-way authentication). // Create a TLS Socket connection (for one-way authentication).
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// Subscribe to TLS Socket connection events. // Subscribe to TLS Socket connection events.
tcp.on('message', value => { tlsTwoWay.on('message', value => {
console.log("on message") console.log("on message")
let buffer = value.message let buffer = value.message
let dataView = new DataView(buffer) let dataView = new DataView(buffer)
...@@ -271,10 +272,10 @@ TLS Socket connection process on the client: ...@@ -271,10 +272,10 @@ TLS Socket connection process on the client:
} }
console.log("on connect received:" + str) console.log("on connect received:" + str)
}); });
tcp.on('connect', () => { tlsTwoWay.on('connect', () => {
console.log("on connect") console.log("on connect")
}); });
tcp.on('close', () => { tlsTwoWay.on('close', () => {
console.log("on close") console.log("on close")
}); });
...@@ -306,16 +307,16 @@ TLS Socket connection process on the client: ...@@ -306,16 +307,16 @@ TLS Socket connection process on the client:
console.log(data); console.log(data);
}); });
// Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events. // Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tls.close((err) => { tlsTwoWay.close((err) => {
if (err) { if (err) {
console.log("close callback error = " + err); console.log("close callback error = " + err);
} else { } else {
console.log("close success"); console.log("close success");
} }
tls.off('message'); tlsTwoWay.off('message');
tls.off('connect'); tlsTwoWay.off('connect');
tls.off('close'); tlsTwoWay.off('close');
}); });
``` ```
......
...@@ -34,7 +34,7 @@ There are two roles in **DataShare**: ...@@ -34,7 +34,7 @@ There are two roles in **DataShare**:
- Data provider: adds, deletes, modifies, and queries data, opens files, and shares data. - Data provider: adds, deletes, modifies, and queries data, opens files, and shares data.
- Data consumer: accesses the data provided by the provider using **DataShareHelper**. - Data consumer: accesses the data provided by the provider using **DataShareHelper**.
### Data Provider Application Development (Only for System Applications) ### Data Provider Application Development (for System Applications Only)
[DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override these APIs as required. [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override these APIs as required.
......
...@@ -15,11 +15,11 @@ import pointer from '@ohos.multimodalInput.pointer'; ...@@ -15,11 +15,11 @@ import pointer from '@ohos.multimodalInput.pointer';
The following table lists the common APIs for mouse pointer management. For details about the APIs, see [ohos.multimodalInput.pointer](../reference/apis/js-apis-pointer.md). The following table lists the common APIs for mouse pointer management. For details about the APIs, see [ohos.multimodalInput.pointer](../reference/apis/js-apis-pointer.md).
| Instance | API | Description | | Instance | API | Description |
| ------- | ------------------------------------------------------------ | --------------------------------------------------------------- | | ------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| pointer | function isPointerVisible(callback: AsyncCallback\<boolean>): void; | Checks the visible status of the mouse pointer. | | pointer | function isPointerVisible(callback: AsyncCallback\<boolean>): void; | Checks the visible status of the mouse pointer. |
| pointer | function setPointerVisible(visible: boolean, callback: AsyncCallback\<void>): void; | Sets the visible status of the mouse pointer. This setting takes effect for the mouse pointer globally. | | pointer | function setPointerVisible(visible: boolean, callback: AsyncCallback\<void>): void; | Sets the visible status of the mouse pointer. This setting takes effect for the mouse pointer globally.|
| pointer | function setPointerStyle(windowId: number, pointerStyle: PointerStyle, callback: AsyncCallback\<void>): void; | Sets the mouse pointer style. This setting takes effect for the mouse pointer style of a specified window. | | pointer | function setPointerStyle(windowId: number, pointerStyle: PointerStyle, callback: AsyncCallback\<void>): void; | Sets the mouse pointer style. This setting takes effect for the mouse pointer style of a specified window. |
| pointer | function getPointerStyle(windowId: number, callback: AsyncCallback\<PointerStyle>): void; | Obtains the mouse pointer style. | | pointer | function getPointerStyle(windowId: number, callback: AsyncCallback\<PointerStyle>): void; | Obtains the mouse pointer style. |
## Hiding the Mouse Pointer ## Hiding the Mouse Pointer
...@@ -77,43 +77,48 @@ When designing a color picker, you can have the mouse pointer switched to the co ...@@ -77,43 +77,48 @@ When designing a color picker, you can have the mouse pointer switched to the co
5. Set the mouse pointer to the default style. 5. Set the mouse pointer to the default style.
```js ```js
import pointer from '@ohos.multimodalInput.pointer';
import window from '@ohos.window'; import window from '@ohos.window';
// 1. Enable the color pickup function. // 1. Enable the color pickup function.
// 2. Obtain the window ID. // 2. Obtain the window ID.
window.getTopWindow((error, windowClass) => { window.getLastWindow(this.context, (error, windowClass) => {
windowClass.getProperties((error, data) => { if (error.code) {
var windowId = data.id; console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
if (windowId < 0) { return;
console.log(`Invalid windowId`); }
return; var windowId = windowClass.getWindowProperties().id;
} if (windowId < 0) {
try { console.log(`Invalid windowId`);
// 3. Set the mouse pointer to the color picker style. return;
pointer.setPointerStyle(windowId, pointer.PointerStyle.COLOR_SUCKER).then(() => { }
console.log(`Successfully set mouse pointer style`); try {
}); // 3. Set the mouse pointer to the color picker style.
} catch (error) { pointer.setPointerStyle(windowId, pointer.PointerStyle.COLOR_SUCKER).then(() => {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`); console.log(`Successfully set mouse pointer style`);
} });
}); } catch (error) {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(`message`)}`);
}
}); });
// 4. End color pickup. // 4. End color pickup.
window.getTopWindow((error, windowClass) => { window.getLastWindow(this.context, (error, windowClass) => {
windowClass.getProperties((error, data) => { if (error.code) {
var windowId = data.id; console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
if (windowId < 0) { return;
console.log(`Invalid windowId`); }
return; var windowId = windowClass.getWindowProperties().id;
} if (windowId < 0) {
try { console.log(`Invalid windowId`);
// 5. Set the mouse pointer to the default style. return;
pointer.setPointerStyle(windowId, pointer.PointerStyle.DEFAULT).then(() => { }
console.log(`Successfully set mouse pointer style`); try {
}); // 5. Set the mouse pointer to the default style.
} catch (error) { pointer.setPointerStyle(windowId, pointer.PointerStyle.DEFAULT).then(() => {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`); console.log(`Successfully set mouse pointer style`);
} });
}); } catch (error) {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(`message`)}`);
}
}); });
``` ```
...@@ -45,7 +45,7 @@ The following table provides only a brief description of related APIs. For detai ...@@ -45,7 +45,7 @@ The following table provides only a brief description of related APIs. For detai
The following example illustrates how to log and subscribe to button click events of users. The following example illustrates how to log and subscribe to button click events of users.
1. Create an eTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **entryability** > **EntryAbility.ts**, and double-click **EntryAbility.ts**. Then, add an event watcher to subscribe to button click events. The complete sample code is as follows: 1. Create an ArkTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **entryability** > **EntryAbility.ts**, and double-click **EntryAbility.ts**. Then, add an event watcher to subscribe to button click events. The complete sample code is as follows:
```js ```js
import hilog from '@ohos.hilog'; import hilog from '@ohos.hilog';
......
...@@ -2,23 +2,21 @@ ...@@ -2,23 +2,21 @@
## How do I obtain the DPI of a device? ## How do I obtain the DPI of a device?
Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 Applicable to: OpenHarmony 3.2 Beta5, stage model of API version 9
Import the **\@ohos.display** module and call the **getDefaultDisplay** API.
Example: Import the **@ohos.display** module and call the **getDefaultDisplaySync** API.
**Example**
``` ```
import display from '@ohos.display'; import display from '@ohos.display';
display.getDefaultDisplay((err, data) => { let displayClass = null;
if (err.code) { try {
console.error('Test Failed to obtain the default display object. Code: ' + JSON.stringify(err)); displayClass = display.getDefaultDisplaySync();
return; console.info('Test densityDPI:' + JSON.stringify(data.densityDPI));
} } catch (exception) {
console.info('Test Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception));
console.info('Test densityDPI:' + JSON.stringify(data.densityDPI)); }
});
``` ```
## How do I obtain the type of the device where the application is running? ## How do I obtain the type of the device where the application is running?
......
...@@ -12,10 +12,10 @@ ...@@ -12,10 +12,10 @@
- [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) - [AVPlayer Development (Recommended)](avplayer-playback.md)
- [AVRecorder Development (Recommended)](avrecorder.md) - [AVRecorder Development (Recommended)](avrecorder.md)
- [Audio Playback Development (To Be Deprecated)](audio-playback.md) - [Audio Playback Development (To Be Deprecated Soon)](audio-playback.md)
- [Audio Recording Development (To Be Deprecated)](audio-recorder.md) - [Audio Recording Development (To Be Deprecated Soon)](audio-recorder.md)
- [Video Playback Development (To Be Deprecated)](video-playback.md) - [Video Playback Development (To Be Deprecated Soon)](video-playback.md)
- [Video Recording Development (To Be Deprecated)](video-recorder.md) - [Video Recording Development (To Be Deprecated Soon)](video-recorder.md)
- AVSession - AVSession
- [AVSession Overview](avsession-overview.md) - [AVSession Overview](avsession-overview.md)
......
...@@ -292,13 +292,13 @@ export class AVPlayerDemo { ...@@ -292,13 +292,13 @@ export class AVPlayerDemo {
async avPlayerDemo() { async avPlayerDemo() {
// Create an AVPlayer instance. // Create an AVPlayer instance.
this.avPlayer = await media.createAVPlayer() this.avPlayer = await media.createAVPlayer()
let fdPath = 'fd://' let fileDescriptor = undefined
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. // Use getRawFileDescriptor of the resource management module to obtain the media assets in the application, and use the fdSrc attribute of the AVPlayer to initialize the media assets.
// 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. // For details on the fd/offset/length parameter, see the Media API. The globalThis.abilityContext parameter is a system environment variable and is saved as a global variable on the main page during the system boost.
let path = pathDir + '/H264_AAC.mp4' await globalThis.abilityContext.resourceManager.getRawFileDescriptor('H264_AAC.mp4').then((value) => {
let file = await fs.open(path) fileDescriptor = {fd: value.fd, offset: value.offset, length: value.length}
fdPath = fdPath + '' + file.fd })
this.avPlayer.url = fdPath this.avPlayer.fdSrc = fileDescriptor
} }
} }
``` ```
......
...@@ -53,10 +53,10 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform ...@@ -53,10 +53,10 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform
// Configure the parameters based on the audio file format. // Configure the parameters based on the audio file format.
SLDataFormat_PCM format_pcm = { SLDataFormat_PCM format_pcm = {
SL_DATAFORMAT_PCM, SL_DATAFORMAT_PCM, // Input audio format.
OHOS::AudioStandard::AudioChannel::MONO, 1, // Mono channel.
OHOS::AudioStandard::AudioSamplingRate::SAMPLE_RATE_44100, SL_SAMPLINGRATE_44_1, // Sampling rate, 44100 Hz.
OHOS::AudioStandard::AudioSampleFormat::SAMPLE_S16LE, SL_PCMSAMPLEFORMAT_FIXED_16, // Audio sampling format, a signed 16-bit integer in little-endian format.
0, 0,
0, 0,
0 0
......
# Notification # Notification
- [Notification Overview](notification-overview.md) - [Notification Overview](notification-overview.md)
- [Notification Subscription (Open Only to System Applications)](notification-subscription.md) - [Notification Subscription (for System Applications)](notification-subscription.md)
- [Enabling Notification](notification-enable.md) - [Enabling Notification](notification-enable.md)
- Publishing a Notification - Publishing a Notification
- [Publishing a Basic Notification](text-notification.md) - [Publishing a Basic Notification](text-notification.md)
......
# Notification Subscription (Open Only to System Applications) # Notification Subscription (for System Applications Only)
To receive notifications, an application must subscribe to notifications first. The notification subsystem provides two types of subscription APIs, allowing applications to subscribe to notifications from all applications or notifications from a specific application. To receive notifications, an application must subscribe to notifications first. The notification subsystem provides two types of subscription APIs, allowing applications to subscribe to notifications from all applications or notifications from a specific application.
......
...@@ -127,10 +127,10 @@ The following table describes the APIs for notification publishing. You specify ...@@ -127,10 +127,10 @@ The following table describes the APIs for notification publishing. You specify
Below is an example of the multi-line notification. Below is an example of the multi-line notification.
![en-us_image_0000001417062446](figures/en-us_image_0000001417062446.png) ![en-us_image_0000001417062446](figures/en-us_image_0000001417062446.png)
- In addition to the parameters in the normal text notification, the picture-attached text notification provides the **picture**, **briefText**, and **expandedTitle** parameters. The value of **picture** is a pixel map that does not exceed 2 MB. - In addition to the parameters in the normal text notification, the picture-attached text notification provides the **picture**, **briefText**, and **expandedTitle** parameters. The value of **picture** is a [PixelMap](../reference/apis/js-apis-image.md#pixelmap7) object that does not exceed 2 MB.
```ts ```ts
let notificationPicture: PixelMap = undefined; // Obtain the pixel map information. let imagePixelMap: PixelMap = undefined; // Obtain the PixelMap information.
let notificationRequest: notificationManager.NotificationRequest = { let notificationRequest: notificationManager.NotificationRequest = {
id: 1, id: 1,
content: { content: {
...@@ -141,7 +141,7 @@ The following table describes the APIs for notification publishing. You specify ...@@ -141,7 +141,7 @@ The following table describes the APIs for notification publishing. You specify
additionalText: 'test_additionalText', additionalText: 'test_additionalText',
briefText: 'test_briefText', briefText: 'test_briefText',
expandedTitle: 'test_expandedTitle', expandedTitle: 'test_expandedTitle',
picture: notificationPicture picture: imagePixelMap
} }
} }
} }
......
# Quick Start # Quick Start
- Getting Started - Getting Started
- [Before You Start](start-overview.md) - [Before You Start](start-overview.md)
- [Getting Started with ArkTS in Stage Model](start-with-ets-stage.md) - [Getting Started with ArkTS in Stage Model](start-with-ets-stage.md)
...@@ -10,7 +11,6 @@ ...@@ -10,7 +11,6 @@
- Application Package Structure - Application Package Structure
- [Application Package Structure in Stage Model](application-package-structure-stage.md) - [Application Package Structure in Stage Model](application-package-structure-stage.md)
- [Application Package Structure in FA Model](application-package-structure-fa.md) - [Application Package Structure in FA Model](application-package-structure-fa.md)
- [HAR File Structure](har-structure.md)
- Multi-HAP Mechanism - Multi-HAP Mechanism
- [Multi-HAP Design Objectives](multi-hap-objective.md) - [Multi-HAP Design Objectives](multi-hap-objective.md)
- [Multi-HAP Build View](multi-hap-build-view.md) - [Multi-HAP Build View](multi-hap-build-view.md)
...@@ -18,6 +18,16 @@ ...@@ -18,6 +18,16 @@
- [Multi-HAP Usage Rules](multi-hap-rules.md) - [Multi-HAP Usage Rules](multi-hap-rules.md)
- [Multi-HAP Operation Mechanism and Data Communication Modes](multi-hap-principles.md) - [Multi-HAP Operation Mechanism and Data Communication Modes](multi-hap-principles.md)
- [Application Installation and Uninstallation Process](application-package-install-uninstall.md) - [Application Installation and Uninstallation Process](application-package-install-uninstall.md)
- [Application Package Update Process](application-package-update.md)
- Shared Package
- [Shared Package Overview](shared-guide.md)
- [HAR](har-package.md)
- HSP
- [In-Application HSP Development](in-app-hsp.md)
- [Inter-Application HSP Development (for System Applications Only)](cross-app-hsp.md)
- Quick Fix
- [Quick Fix Overview](quickfix-principles.md)
- [CLI-based Quick Fix Development](quickfix-debug.md)
- Application Configuration Files in Stage Model - Application Configuration Files in Stage Model
- [Application Configuration File Overview (Stage Model)](application-configuration-file-overview-stage.md) - [Application Configuration File Overview (Stage Model)](application-configuration-file-overview-stage.md)
- [app.json5 Configuration File](app-configuration-file.md) - [app.json5 Configuration File](app-configuration-file.md)
......
# Application Package Structure in Stage Model # Application Package Structure in Stage Model
To develop an application based on the [stage model](application-configuration-file-overview-stage.md), it is essential to understand the structure of the application package created after the application is built and packaged. To develop an application based on the [stage model](application-configuration-file-overview-stage.md), it will be helpful if you have a basic understanding of the structure of the application package created after the application is built and packaged, as well as the related basic concepts.
- In development, an application contains one or more modules. You can [create modules](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3) in the application project in [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio/). As a basic functional unit of an OpenHarmony application/service, a module contains source code, resource files, third-party libraries, and application/service configuration files, and can be built and run independently. Modules can be classified as Ability or Library. A module of the Ability type is built into a Harmony Ability Package (HAP) file in .hap format, and a module of the Library type is built into a [Harmony Ability Resources (HAR) file](har-structure.md) in .tgz format. - In development, an application contains one or more modules. You can [create modules](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3) in the application project in [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio/). As a basic functional unit of an OpenHarmony application/service, a module contains source code, resource files, third-party libraries, and application/service configuration files, and can be built and run independently. Modules can be classified as Ability or Library. A module of the Ability type is built into a Harmony Ability Package (HAP) file, and a module of the Library type is built into a [Harmony Archive (HAR)](har-package.md) file or a [Harmony Shared Package (HSP)](shared-guide.md).
A module can contain one or more [UIAbility](../application-models/uiability-overview.md) components, as shown in the figure below. A module can contain one or more [UIAbility](../application-models/uiability-overview.md) components, as shown in the figure below.
**Figure 1** Relationship between modules and UIAbility components **Figure 1** Relationship between modules and UIAbility components
![ability-and-module](figures/ability-and-module.png) ![ability-and-module](figures/ability-and-module.png)
Unless otherwise specified, the modules described in this document refer to the modules of the Ability type. Unless otherwise specified, the modules described in this document refer to the modules of the Ability type.
- As aforementioned, you can build an application into one or more HAP files. The HAP file is the basic unit for installing an application. It provides code, resources, third-party libraries, and a configuration file. HAP files can be classified as Entry or Feature. - As aforementioned, you can build an application into one or more HAP files. The HAP file is the basic unit for installing an application. It provides code, resources, third-party libraries, and a configuration file. HAP files can be classified as Entry or Feature.
- HAP of the entry type: main module of the application, whose **type** field is set to **"entry"** in the [module.json5](module-configuration-file.md) file. In an application, each type of device supports only one HAP of the entry type, which is typically used to implement the application's entry screen, entry icon, or headline feature. - HAP of the entry type: main module of the application, whose **type** field is set to **"entry"** in the [module.json5](module-configuration-file.md) file. In an application, each type of device supports only one HAP of the entry type, which is typically used to implement the application's entry screen, entry icon, or headline feature.
...@@ -27,6 +27,6 @@ To develop an application based on the [stage model](application-configuration-f ...@@ -27,6 +27,6 @@ To develop an application based on the [stage model](application-configuration-f
- The **module.json** file is the configuration file indispensable in a HAP file. It consists of **module.json5** and **app.json5** in the project configuration. While DevEco Studio provides default configuration, you must modify the configuration as needed. For details about the configuration fields, see [Application Configuration Files in Stage Model](application-configuration-file-overview-stage.md). - The **module.json** file is the configuration file indispensable in a HAP file. It consists of **module.json5** and **app.json5** in the project configuration. While DevEco Studio provides default configuration, you must modify the configuration as needed. For details about the configuration fields, see [Application Configuration Files in Stage Model](application-configuration-file-overview-stage.md).
- The **pack.info** file describes the HAP attributes in the bundle, for example, **bundleName** and **versionCode** in **app** and **name**, **type**, and **abilities** in **module**. The file is automatically generated when DevEco Studio generates the bundle. - The **pack.info** file describes the HAP attributes in the bundle, for example, **bundleName** and **versionCode** in **app** and **name**, **type**, and **abilities** in **module**. The file is automatically generated when DevEco Studio generates the bundle.
**Figure 2** Application package structure in stage model **Figure 2** Application package structure in stage model
![app-pack-stage](figures/app-pack-stage.png) ![app-pack-stage](figures/app-pack-stage.png)
\ No newline at end of file
# Application Package Update Process
The OpenHarmony bundle manager service allows application packages to be updated under the following scenarios:
1. In the application market: The application market notifies the user of an available update, and the user can install the update by following the onscreen instructions.
2. In the application: When the application for which an update is available starts up, the application market notifies the user of the update, and the user can install the update by following the onscreen instructions.
# Inter-Application HSP Development
An inter-application Harmony Shared Package (HSP) is a file used for code and resource sharing between the host application and other applications.
The host application of an inter-application HSP is a special form of application, which consists of only one HSP. Instead of running independently on a device, the host application runs by being referenced by dependencies of common application modules. When a common application is running, it can invoke capabilities provided by the inter-application HSP dynamically as needed.
## Precautions
1. The code of an inter-application HSP runs in the application process. When invoking the code, implement an exception capture and fault tolerance mechanism to avoid stability issues caused by malfunctioning of the inter-application HSP.
2. An application can depend on multiple inter-application HSP files at the same time.
3. The inter-application HSP may slow down the startup of the application that depends on it. To avoid significant increase in the startup delay, limit the number of inter-application HSP dependencies within 16.
4. Third-party developers can only use the system-provided inter-application HSP files.
## Inter-Application HSP Usage
An inter-application HSP works by combining the following parts:
[HAR](har-package.md): contains only objects and methods to be exported and therefore comes in a small size. By integrating the HAR into your application project, you can call the objects and methods therein to implement features.
HSP: contains the actual implementation code, including the JS/TS code, C++ libraries, resources, and configuration files. It is either released to the application market or integrated into the system version.
### Integrating the HAR in an Inter-Application HSP
Define the interfaces to be exported in the **index.d.ets** file in the HAR, which is the entry to the declaration file exported by the inter-application HSP. The path of the **index.d.ets** file is as follows:
```
src
├── main
| └── module.json5
├── index.d.ets
└── package.json
```
Below is an example of the **index.d.ets** file content:
```ts
@Component
export declare struct UIComponent {
build():void;
}
export declare function hello(): string;
export declare function foo1(): string;
export declare function foo2(): string;
export declare function nativeHello(): string;
```
In the example, **UIComponent** is an ArkUI component, **hello()**, **foo1()**, and **foo2()** are TS methods, and **nativeHello()** is an native method. Specific implementation is as follows:
#### ArkUI Components
The following is an implementation example of ArkUI components in the HSP:
```ts
// lib/src/main/ets/ui/MyUIComponent.ets
@Component
export struct UIComponent {
@State message: string = 'Hello World'
build() {
Column() {
Text(this.message)
.fontSize(32)
.padding(8)
.fontColor(0xffffff)
.backgroundColor(0x0000ff)
}.padding(8).width('100%')
}
}
```
#### **TS Methods**
The following is an implementation example of TS methods in the HSP:
```ts
export function hello(name: string): string {
return "hello + " + name;
}
export function foo1() {
return "foo1";
}
export function foo2() {
return "foo2";
}
```
#### **Native Methods**
The following is an implementation example of native methods in the HSP:
```C++
#include "napi/native_api.h"
#include <js_native_api.h>
#include <js_native_api_types.h>
#include <string>
const std::string libname = "liba";
const std::string version = "v10001";
static napi_value Hello(napi_env env, napi_callback_info info) {
napi_value ret;
std::string msg = libname + ":native hello, " + version;
napi_create_string_utf8(env, msg.c_str(), msg.length(), &ret);
return ret;
}
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
napi_property_descriptor desc[] = {
{"nativeHello", nullptr, Hello, nullptr, nullptr, nullptr, napi_default, nullptr}};
napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
return exports;
}
EXTERN_C_END
static napi_module demoModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "liba",
.nm_priv = ((void *)0),
.reserved = {0},
};
extern "C" __attribute__((constructor)) void RegisterLibaModule(void) {
napi_module_register(&demoModule);
}
```
### Using the Capabilities Exported from the HAR
To start with, [configure dependency](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434#section89674298391) on the HAR. The dependency information will then be generated in the **module.json** file of the corresponding module, as shown in the following:
```json
"dependencies": [
{
"bundleName": "com.share.liba",
"moduleName": "liba",
"versionCode": 10001
}
]
```
In the preceding information, **bundleName**, **moduleName**, and **versionCode** indicate the bundle name, module name, and version number of the inter-application HSP, respectively.
#### Referencing ArkUI Components in the HAR
After configuring the dependency on the HAR, you can reference ArkUI components exported from the HAR by using **import**. The sample code is as follows:
``` ts
import { UIComponent } from 'liba'
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
// Reference the ArkUI component in the HAR.
UIComponent()
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
#### Referencing TS Classes and Methods in the HAR
To reference the TS classes and methods exported from the HAR, use **import** as follows:
``` ts
import { foo1 } from 'liba'
import { foo2 } from 'liba'
@Component
struct Index {
build() {
Row() {
Column() {
Button('Button')
.onClick(()=>{
// Reference the TS methods in the HAR.
foo1();
foo2();
})
}
.width('100%')
}
.height('100%')
}
}
```
#### Referencing Native Methods in the HAR
To reference the native methods exported from the HAR, use **import** as follows:
``` ts
import { nativeHello } from 'liba'
@Component
struct Index {
build() {
Row() {
Column() {
Button('Button')
.onClick(()=>{
// Reference the native method in the HAR.
nativeHello();
})
}
.width('100%')
}
.height('100%')
}
}
```
## Inter-Application HSP Distribution
Inter-application HSPs are not completely integrated into an application. They are distributed by being preset in the system version or installed with an application on the device. To be specific:
1. Some frequently-used inter-application HSPs are preset in the system version.
2. When a user downloads an application from the application market, if the application market detects that the application depends on one or more inter-application HSPs and any of these HSPs are not installed on the target device, it will download the application as well as the missing HSPs for the user. In this way, the application can use the features shared through the HSPs properly.
### Inter-Application HSP Debugging Mode
You can debug an inter-application HSP after it is distributed to a device. If the aforementioned distribution methods are not applicable, you can distribute the HSP by running **bm** commands. The procedure is as follows:
> **NOTE**
>
> Do not reverse steps 2 and 3. Otherwise, your application will fail to be installed due to a lack of the required inter-application HSP. For more information about the **bm** commands, see [Bundle Management](../../readme/bundle-management.md).
1. Obtain the inter-application HSP installation package.
2. Run the following **bm** command to install the inter-application HSP.
```
bm install -s sharebundle.hsp
```
3. Run the following **bm** command to install the HAP file of your application.
```
bm install -p feature.hap
```
4. Start your application and start debugging.
...@@ -16,7 +16,7 @@ Manually download the system-specific full SDK package from the mirror. For deta ...@@ -16,7 +16,7 @@ Manually download the system-specific full SDK package from the mirror. For deta
## Checking the Local SDK Location ## Checking the Local SDK Location
In this example, an eTS project is used. For a JS project, replace **ets** with **js**. In this example, an ArkTS project is used. For a JS project, replace **ets** with **js**.
In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the location of the local SDK. In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the location of the local SDK.
......
# HAR
A Harmony Archive (HAR) is a static shared package that can contain code, C++ libraries, resources, and configuration files. It enables modules and projects to share code related to ArkUI components, resources, and more. Unlike a Harmony Ability Package (HAP), a HAR cannot be independently installed on a device. Instead, it can be referenced only as the dependency of an application module.
## Creating a HAR Module
You can kickstart your HAR module development with the module template of the **Library** type in DevEco Studio. By default, obfuscation is disabled for the HAR module. To enable this feature, set **artifactType** in the **build-profile.json5** file of the HAR module to **obfuscation** as follows:
```json
{
"apiType": "stageMode",
"buildOption": {
"artifactType": "obfuscation"
}
}
```
The value options of **artifactType** are as follows, and the default value is **original**:
- **original**: Code is not obfuscated.
- **obfuscation**: Code is obfuscated using Uglify.
When obfuscation is enabled, DevEco Studio compiles, obfuscates, and compresses code during HAR building, thereby protecting your code assets.
> **NOTE**
>
> If **artifactType** is set to **obfuscation**, **apiType** must be set to **stageMode**, because obfuscation is available only in the stage model.
## Precautions for HAR Development
- The HAR does not support the declaration of **abilities** and **extensionAbilities** in its configuration file.
- The HAR does not support the declaration of pages in its configuration file.
- The HAR does not support **worker** configuration under **buildOption** in the **build-profile.json5** file.
- The HAR of the FA model and that of the stage model cannot be referenced by each other.
- The HAR of the stage model cannot reference content in the **AppScope** folder. This is because the content in the **AppScope** folder is not packaged into the HAR during compilation and building.
## Exporting ArkUI Components, APIs, and Resources of the HAR
The **index.ets** file acts as the entry of the HAR export declaration file and is where the HAR exports APIs. This file is automatically generated by DevEco Studio by default. You can specify another file as the entry declaration file in the **main** field in the **package.json** file of the module. The code snippet is as follows:
```json
{
"main": "index.ets"
}
```
### Exporting ArkUI Components
Use **export** to export the ArkUI components. The code snippet is as follows:
```js
// library/src/main/ets/components/MainPage/MainPage.ets
@Component
export struct MainPage {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
In the **index.ets** file, declare the APIs that the HAR exposes to external systems. The code snippet is as follows:
```js
// library/index.ets
export { MainPage } from './src/main/ets/components/MainPage/MainPage'
```
### Exporting TS Classes and Methods
Use **export** to export TS classes and methods. Multiple TS classes and methods can be exported at the same time. The code snippet is as follows:
```js
// library/src/main/ts/test.ets
export class Log {
static info(msg) {
console.info(msg);
}
}
export function func() {
return "har func";
}
export function func2() {
return "har func2";
}
```
In the **index.ets** file, declare the APIs that the HAR exposes to external systems. The code snippet is as follows:
```js
// library/index.ets
export { Log } from './src/main/ts/test'
export { func } from './src/main/ts/test'
export { func2 } from './src/main/ts/test'
```
### Resources
Resources are packed into the HAR when it is being compiled and packaged. During compilation and building of a HAP, DevEco Studio collects resource files from the HAP module and its dependent modules. If the resource files of different modules have the same name, DevEco Studio overwrites the resource files based on the following priorities (in descending order):
- AppScope (supported only by the stage model of API version 9)
- Modules in the HAP file
- If resource conflicts occur between dependent HAR modules, they are overwritten based on the dependency sequence. (The module that is higher in the dependency sequence list has higher priority.)
## Referencing ArkUI Components, APIs, and Resources in the HAR
To start with, [configure dependency](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434#section89674298391) on the HAR.
### Reference ArkUI Components in the HAR
After configuring the dependency on the HAR, you can reference ArkUI components exported from the HAR by using **import**. The sample code is as follows:
```js
// entry/src/main/ets/pages/index.ets
import { MainPage } from "@ohos/library"
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
// Reference the ArkUI component in the HAR.
MainPage()
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
### Referencing TS Classes and Methods in the HAR
To reference the TS classes and methods exported from the HAR, use **import** as follows:
```js
// entry/src/main/ets/pages/index.ets
import { Log } from "@ohos/library"
import { func } from "@ohos/library"
@Entry
@Component
struct Index {
build() {
Row() {
Column() {
Button('Button')
.onClick(()=>{
// Reference TS classes and methods in the HAR.
Log.info("har msg");
func();
})
}
.width('100%')
}
.height('100%')
}
}
```
### Referencing Resources in the HAR
Use **$r** to reference resources in the HAR. For example, add the **name: hello_har** string (defined in the **string.json** file) and **icon_har.png** image to the **src/main/resources** directory of the HAR module, and then reference the string and image in the entry module. The code snippet is as follows:
```js
// entry/src/main/ets/pages/index.ets
@Entry
@Component
struct Index {
build() {
Row() {
Column() {
// Reference the string in the HAR.
Text($r("app.string.hello_har"))
.fontSize(50)
.fontWeight(FontWeight.Bold)
// Reference the image in the HAR.
Image($r("app.media.icon_har"))
}
.width('100%')
}
.height('100%')
}
}
```
# HAR File Structure
The OpenHarmony Archive (HAR) file enables code to be shared among multiple modules or projects. Unlike a Harmony Ability Package (HAP) file, a HAR file cannot be independently installed on a device. Instead, it can only be referenced as the dependency of an application module.
A HAR file is the build product of a [module](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3) of the Library type in a DevEco Studio project.
As a static shared package in OpenHarmony, the [HAR file](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434) can contain the source code, C++ libraries, resource files, and the **module.json** file (in stage model) or **config.json** file (in FA model).
# In-Application HSP Development
An in-application Harmony Shared Package (HSP) is a file used for code and resource sharing within an application (called the host application) and can only be invoked by a HAP or HSP of the same application.
The in-application HSP is released with the Application Package (App Pack) of the host application and has the same bundle name and lifecycle as the host application.
## Developing an In-Application HSP
You can kickstart your HSP development with the HSP template in DevEco Studio. In this example, an HSP module named **library** is created. The basic project directory structure is as follows:
```
library
├── src
│ └── main
│ ├── ets
│ │ ├── pages
│ │ └── index.ets
│ ├── resources
│ └── module.json5
└── package.json
```
In the **module.json5** file, set **type** to **shared** for the HSP.
```json
{
"type": "shared"
}
```
The HSP provides capabilities for external systems by exporting APIs in the entry file. Specify the entry file in **main** in the **package.json** file. For example:
```json
{
"main": "./src/main/ets/index.ets"
}
```
### Exporting TS Classes and Methods
Use **export** to export TS classes and methods. The sample code is as follows:
```ts
// library/src/main/ets/utils/test.ts
export class Log {
static info(msg) {
console.info(msg);
}
}
export function add(a: number, b: number) {
return a + b;
}
export function minus(a: number, b: number) {
return a - b;
}
```
In the entry file **index.ets**, declare the APIs to be exposed.
```ts
// library/src/main/ets/index.ets
export { Log, add, minus } from './utils/test'
```
### Exporting ArkUI Components
Use **export** to export ArkUI components. The sample code is as follows:
```ts
// library/src/main/ets/components/MyTitleBar.ets
@Component
export struct MyTitleBar {
build() {
Row() {
Text($r('app.string.library_title'))
.fontColor($r('app.color.white'))
.fontSize(25)
.margin({left:15})
}
.width('100%')
.height(50)
.padding({left:15})
.backgroundColor('#0D9FFB')
}
}
```
In the entry file **index.ets**, declare the APIs to be exposed.
```ts
// library/src/main/ets/index.ets
export { MyTitleBar } from './components/MyTitleBar'
```
#### About Using Resources in the HSP
To reference resources in the **resources** directory of the current HSP module, use **$r** or **$rawfile**.
If a relative path is used, the resources in the HSP caller are referenced instead. For example,
if **Image("common/example.png")** is used in the HSP module, the **\<Image>** component will reference the resource **entry/src/main/ets/common/example.png** in the HSP caller (which is **entry** in this example).
### Exporting Native Methods
The HSP can contain .so files compiled in C++. The HSP indirectly exports the native method in the .so file. In this example, the **multi** method in the **libnative.so** file is exported.
```ts
// ibrary/src/main/ets/utils/nativeTest.ts
import native from "libnative.so"
export function nativeMulti(a: number, b: number) {
return native.multi(a, b);
}
```
In the entry file **index.ets**, declare the APIs to be exposed.
```ts
// library/src/main/ets/index.ets
export { nativeMulti } from './utils/nativeTest'
```
## Using the In-Application HSP
To use APIs in the HSP, first configure the dependency on the HSP in the **package.json** file of the module that needs to call the APIs (called the invoking module). If the HSP and the invoking module are in the same project, the APIs can be referenced locally. The sample code is as follows:
```json
// entry/src/main/module.json5
"dependencies": {
"library": "file:../library"
}
```
You can now call the external APIs of the HSP in the same way as calling the APIs in the HAR.
In this example, the external APIs are the following ones exported from **library**:
```ts
// library/src/main/ets/index.ets
export { Log, add, minus } from './utils/test'
export { MyTitleBar } from './components/MyTitleBar'
export { nativeMulti } from './utils/nativeTest'
```
The APIs can be used as follows in the code of the invoking module:
```ts
// entry/src/main/ets/pages/index.ets
import { Log, add, MyTitleBar, nativeMulti } from "library"
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
MyTitleBar()
Text(this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
Button('add(1, 2)')
.onClick(()=>{
Log.info("add button click!");
this.message = "result: " + add(1, 2);
})
Button('nativeMulti(3, 4)')
.onClick(()=>{
Log.info("nativeMulti button click!");
this.message = "result: " + nativeMulti(3, 4);
})
}
.width('100%')
}
.height('100%')
}
}
```
...@@ -72,7 +72,7 @@ As shown above, the **module.json5** file contains several tags. ...@@ -72,7 +72,7 @@ As shown above, the **module.json5** file contains several tags.
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | Name of the module. The value is a string with a maximum of 31 bytes and must be unique in the entire application. Chinese characters are not allowed.| String| No| | name | Name of the module. The value is a string with a maximum of 31 bytes and must be unique in the entire application. Chinese characters are not allowed.| String| No|
| type | Type of the module. The value can be **entry** or **feature**.<br>- **entry**: main module of the application.<br>- **feature**: dynamic feature module of the application.| String| No| | type | Type of the module. The options are as follows:<br>- **entry**: main module of the application.<br>- **feature**: dynamic feature module of the application.<br>- **har**: static shared module.<br>- **shared**: dynamic shared module.| String| No|
| srcEntry | Code path corresponding to the module. The value is a string with a maximum of 127 bytes.| String| Yes (initial value: left empty)| | srcEntry | Code path corresponding to the module. The value is a string with a maximum of 127 bytes.| String| Yes (initial value: left empty)|
| description | Description of the module. The value is a string with a maximum of 255 bytes or a string resource index.| String| Yes (initial value: left empty)| | description | Description of the module. The value is a string with a maximum of 255 bytes or a string resource index.| String| Yes (initial value: left empty)|
| process | Process name of the current module. The value is a string with a maximum of 31 bytes. If **process** is configured under **HAP**, all UIAbility, DataShareExtensionAbility, and ServiceExtensionAbility components of the application run in the specified process.<br>**NOTE**<br>This tag applies only to system applications and does not take effect for third-party applications.| String| Yes (initial value: value of **bundleName** under **app** in the **app.json5** file)| | process | Process name of the current module. The value is a string with a maximum of 31 bytes. If **process** is configured under **HAP**, all UIAbility, DataShareExtensionAbility, and ServiceExtensionAbility components of the application run in the specified process.<br>**NOTE**<br>This tag applies only to system applications and does not take effect for third-party applications.| String| Yes (initial value: value of **bundleName** under **app** in the **app.json5** file)|
...@@ -150,7 +150,7 @@ Define the **main_pages.json** file under **resources/base/profile** in the deve ...@@ -150,7 +150,7 @@ Define the **main_pages.json** file under **resources/base/profile** in the deve
The **metadata** tag represents the custom metadata of the HAP file. The tag value is an array and contains three subtags: **name**, **value**, and **resource**. The **metadata** tag represents the custom metadata of the HAP file. The tag value is an array and contains three subtags: **name**, **value**, and **resource**.
**Table 3** metadata **Table 3** metadata
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
...@@ -210,9 +210,10 @@ Touching this icon will direct the user to the application details screen in **S ...@@ -210,9 +210,10 @@ Touching this icon will direct the user to the application details screen in **S
To hide an application icon from the home screen, you must configure the **AllowAppDesktopIconHide** privilege. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). To hide an application icon from the home screen, you must configure the **AllowAppDesktopIconHide** privilege. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md).
**Setting the application icon to be displayed on the home screen**: **Setting the application icon to be displayed on the home screen**:
Set **icon**, **label**, and **skills** under **abilities** in the **module.json5** file. In addition, the **skills** configuration must contain **ohos.want.action.home **and **entity.system.home**. Set **icon**, **label**, and **skills** under **abilities** in the **module.json5** file. In addition, make sure the **skills** configuration contains **ohos.want.action.home** and **entity.system.home**.
``` ```
{ {
...@@ -284,7 +285,7 @@ Set **icon**, **label**, and **skills** under **abilities** in the **module.json ...@@ -284,7 +285,7 @@ Set **icon**, **label**, and **skills** under **abilities** in the **module.json
| removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the UIAbility component is destroyed.<br>- **true**: Remove the relevant task from the task list after the UIAbility component is destroyed.<br>- **false**: Do not remove the relevant task from the task list after the UIAbility component is destroyed.| Boolean| Yes (initial value: **false**)| | removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the UIAbility component is destroyed.<br>- **true**: Remove the relevant task from the task list after the UIAbility component is destroyed.<br>- **false**: Do not remove the relevant task from the task list after the UIAbility component is destroyed.| Boolean| Yes (initial value: **false**)|
| orientation | Orientation of the UIAbility component when it is started. The options are as follows:<br>- **unspecified**: automatically determined by the system.<br>- **landscape**: landscape mode.<br>- **portrait**: portrait mode.<br>- **landscape_inverted**: inverted landscape mode.<br>- **portrait_inverted**: inverted portrait mode.<br>- **auto_rotation**: determined by the sensor.<br>- **auto_rotation_landscape**: determined by the sensor in the horizontal direction, including landscape and inverted landscape modes.<br>- **auto_rotation_portrait**: determined by the sensor in the vertical direction, including portrait and inverted portrait modes.<br>- **auto_rotation_restricted**: determined by the sensor when the sensor switch is enabled.<br>- **auto_rotation_landscape_restricted**: determined by the sensor in the horizontal direction, including landscape and inverted landscape modes, when the sensor switch is enabled.<br>- **auto_rotation_portrait_restricted**: determined by the sensor in the vertical direction, including portrait and inverted portrait modes, when the sensor switch is enabled.<br>- **locked**: auto rotation disabled.| String| Yes (initial value: **"unspecified"**)| | orientation | Orientation of the UIAbility component when it is started. The options are as follows:<br>- **unspecified**: automatically determined by the system.<br>- **landscape**: landscape mode.<br>- **portrait**: portrait mode.<br>- **landscape_inverted**: inverted landscape mode.<br>- **portrait_inverted**: inverted portrait mode.<br>- **auto_rotation**: determined by the sensor.<br>- **auto_rotation_landscape**: determined by the sensor in the horizontal direction, including landscape and inverted landscape modes.<br>- **auto_rotation_portrait**: determined by the sensor in the vertical direction, including portrait and inverted portrait modes.<br>- **auto_rotation_restricted**: determined by the sensor when the sensor switch is enabled.<br>- **auto_rotation_landscape_restricted**: determined by the sensor in the horizontal direction, including landscape and inverted landscape modes, when the sensor switch is enabled.<br>- **auto_rotation_portrait_restricted**: determined by the sensor in the vertical direction, including portrait and inverted portrait modes, when the sensor switch is enabled.<br>- **locked**: auto rotation disabled.| String| Yes (initial value: **"unspecified"**)|
| supportWindowMode | Window mode supported by the UIAbility component. The options are as follows:<br>- **fullscreen**: full-screen mode.<br>- **split**: split-screen mode.<br>- **floating**: floating window mode.| String array| Yes (initial value:<br>["fullscreen", "split", "floating"])| | supportWindowMode | Window mode supported by the UIAbility component. The options are as follows:<br>- **fullscreen**: full-screen mode.<br>- **split**: split-screen mode.<br>- **floating**: floating window mode.| String array| Yes (initial value:<br>["fullscreen", "split", "floating"])|
| priority | Priority of the UIAbility component. This attribute applies only to system applications and does not take effect for third-party applications. In the case of [implicit query](../application-models/explicit-implicit-want-mappings.md), UIAbility components with a higher priority are at the higher place of the returned list. The value is an integer ranging from 0 to 10. The greater the value, the higher the priority.| Number| Yes (initial value: **0**)| | priority | Priority of the UIAbility component. In the case of [implicit query](../application-models/explicit-implicit-want-mappings.md), UIAbility components with a higher priority are at the higher place of the returned list. The value is an integer ranging from 0 to 10. The greater the value, the higher the priority.<br>**NOTE**<br>This tag applies only to system applications and does not take effect for third-party applications.| Number| Yes (initial value: **0**)|
| maxWindowRatio | Maximum aspect ratio supported by the UIAbility component. The minimum value is 0.| Number| Yes (initial value: maximum aspect ratio supported by the platform)| | maxWindowRatio | Maximum aspect ratio supported by the UIAbility component. The minimum value is 0.| Number| Yes (initial value: maximum aspect ratio supported by the platform)|
| minWindowRatio | Minimum aspect ratio supported by the UIAbility component. The minimum value is 0.| Number| Yes (initial value: minimum aspect ratio supported by the platform)| | minWindowRatio | Minimum aspect ratio supported by the UIAbility component. The minimum value is 0.| Number| Yes (initial value: minimum aspect ratio supported by the platform)|
| maxWindowWidth | Maximum window width supported by the UIAbility component, in vp. The minimum value is 0, and the value cannot be less than the value of **minWindowWidth** or greater than the maximum window width allowed by the platform. For details about the window size, see [Constraints](../windowmanager/window-overview.md#constraints).| Number| Yes (initial value: maximum window width supported by the platform)| | maxWindowWidth | Maximum window width supported by the UIAbility component, in vp. The minimum value is 0, and the value cannot be less than the value of **minWindowWidth** or greater than the maximum window width allowed by the platform. For details about the window size, see [Constraints](../windowmanager/window-overview.md#constraints).| Number| Yes (initial value: maximum window width supported by the platform)|
...@@ -396,22 +397,22 @@ Example of the **skills** structure: ...@@ -396,22 +397,22 @@ Example of the **skills** structure:
} }
``` ```
**Enhance implicit query** **Enhanced implicit query**
URI-level prefix matching is supported. URI-level prefix matching is supported.
When only **scheme** or a combination of **scheme** and **host** or **scheme**, **host**, and **port** are configured in the configuration file, the configuration is successful if the URI prefixed with the configuration file is passed in. When only **scheme** or a combination of **scheme** and **host** or **scheme**, **host**, and **port** are configured in the configuration file, the configuration is successful if a URI prefixed with the configuration file is passed in.
* The query enhancement involves the following APIs: * The query enhancement involves the following APIs:
[@ohos.bundle.bundleManager](../reference/apis/js-apis-bundleManager.md#bundlemanagerqueryabilityinfo)<br> [@ohos.bundle.bundleManager](../reference/apis/js-apis-bundleManager.md#bundlemanagerqueryabilityinfo)<br>
1. function queryAbilityInfo(want: Want, abilityFlags: number, callback: AsyncCallback<Array<AbilityInfo>>): void;<br> 1. function queryAbilityInfo(want: Want, abilityFlags: number, callback: AsyncCallback<Array\<AbilityInfo>>): void;<br>
2. function queryAbilityInfo(want: Want, abilityFlags: number, userId: number, callback: AsyncCallback<Array<AbilityInfo>>): void;<br> 2. function queryAbilityInfo(want: Want, abilityFlags: number, userId: number, callback: AsyncCallback<Array\<AbilityInfo>>): void;<br>
3. function queryAbilityInfo(want: Want, abilityFlags: number, userId?: number): Promise<Array<AbilityInfo>>; 3. function queryAbilityInfo(want: Want, abilityFlags: number, userId?: number): Promise<Array\<AbilityInfo>>;
* Configuration requirements<br> * Configuration requirements<br>
abilities -> skills -> uris object<br> abilities -> skills -> uris object<br>
Configuration 1: only **scheme = 'http'**<br> Configuration 1: only **scheme = 'http'**<br>
Configuration 2: only **(scheme = 'http' ) + ( host = 'example.com')**<br> Configuration 2: only **(scheme = 'http') + (host = 'example.com')**<br>
Configuration 3: only **(scheme = 'http' ) + ( host = 'example.com' ) + ( port = '8080')**<br> Configuration 3: only **(scheme = 'http') + (host = 'example.com') + (port = '8080')**
* Prefix match<br> * Prefix match<br>
If the value of **uri** under [want](../application-models/want-overview.md) is obtained by calling the **queryAbilityInfo** API: If the value of **uri** under [want](../application-models/want-overview.md) is obtained by calling the **queryAbilityInfo** API:
1. uri = 'https://': No matches<br> 1. uri = 'https://': No matches<br>
...@@ -429,8 +430,6 @@ When only **scheme** or a combination of **scheme** and **host** or **scheme**, ...@@ -429,8 +430,6 @@ When only **scheme** or a combination of **scheme** and **host** or **scheme**,
13. uri = 'http://example.com:9180/path': Matches configuration 1 and configuration 2<br> 13. uri = 'http://example.com:9180/path': Matches configuration 1 and configuration 2<br>
14. uri = 'http://example.com:8080/path': Matches configuration 1, configuration 2, and configuration 3<br> 14. uri = 'http://example.com:8080/path': Matches configuration 1, configuration 2, and configuration 3<br>
## extensionAbilities ## extensionAbilities
The **extensionAbilities** tag represents the configuration of extensionAbilities, which is valid only for the current extensionAbility. The **extensionAbilities** tag represents the configuration of extensionAbilities, which is valid only for the current extensionAbility.
...@@ -446,8 +445,8 @@ The **extensionAbilities** tag represents the configuration of extensionAbilitie ...@@ -446,8 +445,8 @@ The **extensionAbilities** tag represents the configuration of extensionAbilitie
| label | Name of the ExtensionAbility component displayed to users. The value is a string resource index.<br>**NOTE**<br>If **ExtensionAbility** is set to **MainElement** of the current module, this attribute is mandatory and its value must be unique in the application.| String| No| | label | Name of the ExtensionAbility component displayed to users. The value is a string resource index.<br>**NOTE**<br>If **ExtensionAbility** is set to **MainElement** of the current module, this attribute is mandatory and its value must be unique in the application.| String| No|
| type | Type of the ExtensionAbility component. The options are as follows:<br>- **form**: ExtensionAbility of a widget.<br>- **workScheduler**: ExtensionAbility of a Work Scheduler task.<br>- **inputMethod**: ExtensionAbility of an input method.<br>- **service**: service component running in the background.<br>- **accessibility**: ExtensionAbility of an accessibility feature.<br>- **dataShare**: ExtensionAbility for data sharing.<br>- **fileShare**: ExtensionAbility for file sharing.<br>- **staticSubscriber**: ExtensionAbility for static broadcast.<br>- **wallpaper**: ExtensionAbility of the wallpaper.<br>- **backup**: ExtensionAbility for data backup.<br>- **window**: ExtensionAbility of a window. This type of ExtensionAbility creates a window during startup for which you can develop the GUI. The window is then combined with other application windows through **abilityComponent**.<br>- **thumbnail**: ExtensionAbility for obtaining file thumbnails. You can provide thumbnails for files of customized file types.<br>- **preview**: ExtensionAbility for preview. This type of ExtensionAbility can parse the file and display it in a window. You can combine the window with other application windows.<br>- **print**: ExtensionAbility for the print framework.<br>**NOTE**<br>The **service** and **dataShare** types apply only to system applications and do not take effect for third-party applications.| String| No| | type | Type of the ExtensionAbility component. The options are as follows:<br>- **form**: ExtensionAbility of a widget.<br>- **workScheduler**: ExtensionAbility of a Work Scheduler task.<br>- **inputMethod**: ExtensionAbility of an input method.<br>- **service**: service component running in the background.<br>- **accessibility**: ExtensionAbility of an accessibility feature.<br>- **dataShare**: ExtensionAbility for data sharing.<br>- **fileShare**: ExtensionAbility for file sharing.<br>- **staticSubscriber**: ExtensionAbility for static broadcast.<br>- **wallpaper**: ExtensionAbility of the wallpaper.<br>- **backup**: ExtensionAbility for data backup.<br>- **window**: ExtensionAbility of a window. This type of ExtensionAbility creates a window during startup for which you can develop the GUI. The window is then combined with other application windows through **abilityComponent**.<br>- **thumbnail**: ExtensionAbility for obtaining file thumbnails. You can provide thumbnails for files of customized file types.<br>- **preview**: ExtensionAbility for preview. This type of ExtensionAbility can parse the file and display it in a window. You can combine the window with other application windows.<br>- **print**: ExtensionAbility for the print framework.<br>**NOTE**<br>The **service** and **dataShare** types apply only to system applications and do not take effect for third-party applications.| String| No|
| permissions | Permissions required for another application to access the ExtensionAbility component.<br>The value is generally in the reverse domain name notation and contains a maximum of 255 bytes. It is an array of permission names predefined by the system or customized. The name of a customized permission must be the same as the **name** value of a permission defined in the **defPermissions** attribute.| String array| Yes (initial value: left empty)| | permissions | Permissions required for another application to access the ExtensionAbility component.<br>The value is generally in the reverse domain name notation and contains a maximum of 255 bytes. It is an array of permission names predefined by the system or customized. The name of a customized permission must be the same as the **name** value of a permission defined in the **defPermissions** attribute.| String array| Yes (initial value: left empty)|
| uri | Data URI provided by the ExtensionAbility component. The value is a string with a maximum of 255 bytes, in the reverse domain name notation.<br>**NOTE**<br>This attribute is mandatory when **type** of the ExtensionAbility component is set to **dataShare**.| String| Yes (initial value: left empty)| | uri | Data URI provided by the ExtensionAbility component. The value is a string with a maximum of 255 bytes, in the reverse domain name notation.<br>**NOTE**<br>This attribute is mandatory when the type of the **ExtensionAbility** component is set to **dataShare**. | String| Yes (initial value: left empty)|
|skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component.<br>Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application.<br>**NOTE**<br>The **skills** attribute with the entry capability can be configured for the feature-type package of an OpenHarmony application,<br>but not for an OpenHarmony service.| Array| Yes (initial value: left empty)| |skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component.<br>Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application.<br>**NOTE**<br>The **skills** attribute with the entry capability can be configured for the feature-type package of an OpenHarmony application, but not for an OpenHarmony service. | Array| Yes (initial value: left empty)|
| [metadata](#metadata)| Metadata of the ExtensionAbility component.| Object| Yes (initial value: left empty)| | [metadata](#metadata)| Metadata of the ExtensionAbility component.| Object| Yes (initial value: left empty)|
| exported | Whether the ExtensionAbility component can be called by other applications. <br>- **true**: The ExtensionAbility component can be called by other applications.<br>- **false**: The UIAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)| | exported | Whether the ExtensionAbility component can be called by other applications. <br>- **true**: The ExtensionAbility component can be called by other applications.<br>- **false**: The UIAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)|
...@@ -488,11 +487,12 @@ Example of the **extensionAbilities** structure: ...@@ -488,11 +487,12 @@ Example of the **extensionAbilities** structure:
## requestPermissions ## requestPermissions
The **requestPermissions** tage represents a set of permissions that the application needs to request from the system for running correctly. The **requestPermissions** tag represents a set of permissions that the application needs to request from the system for running correctly.
> **NOTE** > **NOTE**
> >
> The permission settings configured in the **requestPermissions** tag apply to the entire application. > - The permission settings configured in the **requestPermissions** tag apply to the entire application.
> - If your application needs to subscribe to an event published by itself and the permissions required for accessing the application are set in the **permissions** tag under **extensionAbilities**, then the application must register the related permissions in the **requestPermissions** tag to receive the event.
**Table 8** requestPermissions **Table 8** requestPermissions
...@@ -540,7 +540,7 @@ The **shortcut** information is identified in **metadata**, where: ...@@ -540,7 +540,7 @@ The **shortcut** information is identified in **metadata**, where:
| shortcutId | ID of the shortcut. The value is a string with a maximum of 63 bytes.| String| No| | shortcutId | ID of the shortcut. The value is a string with a maximum of 63 bytes.| String| No|
| label | Label of the shortcut, that is, the text description displayed for the shortcut. The value can be a string or a resource index to the label, with a maximum of 255 bytes.| String| Yes (initial value: left empty)| | label | Label of the shortcut, that is, the text description displayed for the shortcut. The value can be a string or a resource index to the label, with a maximum of 255 bytes.| String| Yes (initial value: left empty)|
| icon | Icon of the shortcut. The value is an icon resource index.| String| Yes (initial value: left empty)| | icon | Icon of the shortcut. The value is an icon resource index.| String| Yes (initial value: left empty)|
| [wants](../application-models/want-overview.md) | Wants to which the shortcut points. Each want consists of the **bundleName** and **abilityName** sub-attributes.<br>**bundleName**: target bundle name of the shortcut. The value is a string.<br>**abilityName**: target component name of the shortcut. The value is a string.| Object| Yes (initial value: left empty)| | [wants](../application-models/want-overview.md) | Wants to which the shortcut points. Each want consists of the **bundleName** and **abilityName** sub-attributes.<br>- **bundleName**: target bundle name of the shortcut. The value is a string.<br>- **abilityName**: target component name of the shortcut. The value is a string.| Object| Yes (initial value: left empty)|
1. Configure the **shortcuts_config.json** file in **/resource/base/profile/**. 1. Configure the **shortcuts_config.json** file in **/resource/base/profile/**.
...@@ -699,7 +699,7 @@ Configure **metadata** in the **module** tag in the **module.json5** file. ...@@ -699,7 +699,7 @@ Configure **metadata** in the **module** tag in the **module.json5** file.
The **testRunner** tag represents the supported test runner. The **testRunner** tag represents the supported test runner.
**Table 14** testRunner **Table 14** testRunner
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
......
# CLI-based Quick Fix Development
You can use the command-line tool to develop a quick fix file, an expeditious approach to resolve application bugs. In this document, an application with the bundle name of **com.ohos.quickfix** in version 1000000 is used as an example to describe how to develop a quick fix file with the command-line tool.
## Writing the patch.json File
Write a **patch.json** file that meets your project requirements and place it in any directory of the project. (Configuring the **patch.json** file is not supported in DevEco Studio.) Create a **patch.json** file on the local computer. Below is an example of the file content:
```json
{
"app" : {
"bundleName" : "com.ohos.quickfix",
"versionCode": 1000000, // Application version
"versionName" : "1.0.0.1",
"patchVersionCode": 1000000, // Patch version
"patchVersionName" : "1.0.0.1"
},
"module" : {
"name" : "entry",
"type" : "patch",
"deviceTypes" : [
"default",
"tablet"
],
"originalModuleHash": "11223344556677889900" // SHA-256 value of the HAP file to restore
}
}
```
## Generating a Quick Fix File
### Quick Fix for TS Code
* After modifying the TS code file in DevEco Studio and build it into a HAP file, you can find the corresponding .abc file in the project directory, for example, **build\default\cache\default\LegacyCompileETS\jsbundle\temporary\pages\index.abc**.
### Quick Fix for C++ Code
* In DevEco Studio, build the original C++ code into a .so file. Fix bugs in the code and rebuild the code into a new .so file. You can find this .so file in the project directory, for example, **build\default\intermediates\libs\default\arm64-v8a\libentry.so**.
* Locate the **diff.exe** tool in the **toolchains** folder in the local OpenHarmony SDK path. Use this tool to generate a quick fix .so file based on the old and new .so files. The command is as follows:
```shell
$ diff.exe -s Example.z.so -d Example.z.so -p Example.z.so.diff
```
The command contains the following options:
- -**s**: path to the old .so file
- -**d**: path to the new .so file
- -**p**: path of the generated differential file
## Generating a Quick Fix File in .hqf Format
With the preceding **patch.json**, .abc, and .so files, run the following command to generate an .hqf file using the **app_packing_tool.jar** tool in the **toolchains** folder in the local OpenHarmony SDK path:
```shell
$ java -jar app_packing_tool.jar --mode hqf --json-path patch.json --lib-path libs --ets-patch patchs --out-path entry-default-unsigned.hqf --force true
```
The command contains the following options.
| Option|Description | Remarks|
| --- | --- |---|
| mode |Mode. | Mandatory|
| json-path|Path to the **patch.json** file.|Mandatory|
| lib-path|Path to the quick fix .so file. For details about the path, see [Structure of the Quick Fix Package](quickfix-principles.md#structure-of-the-quick-fix-package).|Optional|
| ets-path|Path to the quick fix .abc file.|Optional|
## Signing the Quick Fix File
Use the [hapsigner](../security/hapsigntool-guidelines.md) tool to sign the **entry-default-unsigned.hqf** file, in the same way you sign a HAP file. To be specific, run the following command to use **hap-sign-tool.jar** in the **toolchains** folder in the local OpenHarmony SDK path:
```shell
$ java -jar hap-sign-tool.jar sign-app -keyAlias "OpenHarmony Application Release" -signAlg "SHA256withECDSA" -mode "localSign" -appCertFile "OpenHarmonyApplication.pem" -profileFile "ohos_provision_release.p7b" -inFile "entry-default-unsigned.hqf" -keystoreFile "OpenHarmony.p12" -outFile "entry-signed-release.hqf" -keyPwd "123456" -keystorePwd "123456"
```
## Installing the Quick Fix File
Push the **entry-signed-release.hqf** file to the device.
```shell
hdc.exe file send .\entry-signed-release.hqf /data/
```
Run the following command to install the quick fix file as a patch:
```shell
$ bm quickfix -a -f /data/entry-signed-release.hqf
```
The complete commands are as follows:
```
$ bm quickfix -h
usage: bm quickfix <options>
options list:
-h, --help list available commands
-q, --query indicates query quickfix, used with -b or --bundle-name
-b, --bundle-name <bundle-name> query quickfix status and information by a specified bundle name
-a, --apply indicates apply quickfix, used with -f or --file-path
-f, --file-path <file-path> apply a quickfix file by a specified path
-f, --file-path <file-path> <file-path> ... apply some quickfix files of one bundle
-f, --file-path <bundle-direction> apply quickfix files by direction, under which are quickfix files
```
# Quick Fix Overview
Quick fix is a technical means provided by the OpenHarmony system for developers to fix application bugs in a manner that is far faster than application upgrades. Compared with the full application upgrade, the quick fix provides a better user experience by being smaller and faster. It allows users to fix application bugs quickly, without restarting their application.
## Rules for Using Quick Fix
* The quick fix only works for TypeScript (TS) and C++ code of applications, that is, .abc files (created after TS code compilation) and .so files (created after C++ code compilation). It does not work for resource files.
* No new .abc and .so files are allowed.
* Before deploying a quick fix package, make sure the corresponding application has been installed. Otherwise, the deployment will fail.
* The bundle name and application version number configured in the quick fix package must be the same as those of the installed application. Otherwise, the deployment will fail.
* Make sure the version of the quick fix package to deploy is later than that of the one previously deployed. Otherwise, the deployment will fail.
* The signature information of the quick fix package must be the same as that of the application to be fixed. Otherwise, the deployment will fail.
* Installing an application update will delete quick fix package.
## Structure of the Quick Fix Package
![Quick Fix Package Structure](figures/quick_fix_bundle_struct.png)
<br>The preceding figure shows the structure of the quick fix package released by an OpenHarmony application.
* As shown in the figure, the quick fix package comes in two formats:
* .appqf (Application Quick Fix)
<br> There is a one-to-one mapping between the .appqf file and App Pack of an application. For details, see [Application Package Structure in Stage Model](application-package-structure-stage).
* The .appqf file is used to release OpenHarmony applications to the application market and cannot be directly installed on devices.
* An .appqf file consists of one or more .hqf (Harmony Ability Package Quick Fix) files, which are extracted from the .appqf file by the application market and then distributed to specific devices.
* The .appqf file must contain the developer's signature information before being released to the application market. For details about how to sign the file, see [hapsigner Overview](../security/hapsigntool-overview.md).
* .hqf (Harmony Ability Package Quick Fix)
<br> The .hqf file is a quick fix to bugs in a HAP file. It can be installed on devices. An .hqf file contains .abc and .so files. The .abc files provide the quick fix, and the .so files provide package configuration information as well as the quick fix.
* .abc file: modified TS code in the application, which is a bytecode file created after the build.
* **libs** directory: a collection of .so.diff files, which are differential files of the .so library files, organized by system CPU architecture, such as arm and x86.
* **patch.json**:
<br> This file is used to describe the version information of the .hqf file and is filled in by developers. The details are as follows:
```json
{
"app" : {
"bundleName" : "com.ohos.quickfix",
"versionCode" : 1000000,
"versionName" : "1.0.0",
"patchVersionCode" : 1000000,
"patchVersionName" : "1.0.0"
},
"module" : {
"name" : "entry",
"type" : "patch",
"deviceTypes" : [
"default",
"tablet"
],
"originalModuleHash" : "11223344556677889900"
}
}
```
The following describes the parameters:
| Parameter|Type |Description |Initial Value Allowed|
| --- | --- | --- | --- |
|bundleName | string | Bundle name of the application. | No|
|versionCode | int |Version of the application. | No |
|versionName |string |Version name of the application.| No for the patch|
|patchVersionCode |int |Version of the patch. | No|
|patchVersionName |string |Version name of the patch.| No for the patch|
|name |string |Module name of the application, which is used to restore the module.| No|
|type | string|Type of the patch. The value can only be **patch**.| No|
|deviceTypes |array<string> |Device types supported by the patch.| No|
|originalModuleHash| string |Hash value of the bundle corresponding to the original module name.| No|
## Quick Fix to .abc Files Created After TS Code Compilation
![.abc File Quick Fix](figures/quick_fix_gen_abc.png)
The preceding figure shows the process of creating an .abc file quick fix using the TS compiler.
* An application build creates .abc and .map files. The .abc file is a bytecode file created after TS code compilation. It is used when the application is running. The .map file is an intermediate file created when the TS code is compiled using the TS compiler. It stores information such as functions and classes in the code.
* After bugs in the application are fixed, the application code is compiled again. During the compilation, the difference between the source and the target is obtained based on the preceding .map file and the current TS code, and an .abc file for quick fix is generated based on the difference. This .abc file will be placed in the .hqf file.
## Quick Fix to .so Files Created After C++ Code Compilation
![.so File Quickly Fix](figures/quick_fix_gen_so.png)
The preceding figure shows the process of creating a .so file quick fix using the differential tool.
* The C++ source code of the original application is built into a .so file by using a compiler. The .so file is used when the application is running.
* After bugs in the application are fixed, the C++ code is compiled again into a .so file. With the two .so files before and after bug fixes, the differential tool generates a .so file for quick fix. This .so file will also be placed in the .hqf file.
## Quick Fix Release and Deployment Process
![Quick Fix File Release](figures/quick-fix-devel_release.png)
As shown above, the modules involved in the release process are as follows:
* DevEco Studio: an integrated development environment for developing code projects. It can be used to create a quick fix file based on the original application code and the code after bug fixes, and sign the created quick repair file for release to the application market.
* Application market server: place where you release the quick fix file. It verifies the signature, scans for risks, unpacks and resigns the file, and then distributes the file to the client.
* Application market client: tool that receives the quick fix file from the application market server and triggers installation.
* Bundle manager service: system service used to manage the installation and uninstallation of application packages and quick fix files on the device.
* Quick fix engine: system service used to manage switching to quick fix code on the device. If the target application is running, the quick fix engine instructs it to switch to the quick fix file upon completion of the quick fix file deployment.
* File system: location where the application package and quick repair file are deployed on the device.
In the end-to-end release and deployment process of the quick repair file:
1. DevEco Studio is used to create a quick fix file through building and packaging based on the original application source code and the source code after bug fixes, and sign the created quick fix file.
2. The signed quick repair file is released to the application market, which then distributes the file after verifying the signature, scanning for risks, and unpacking and resigning the file.
3. When the on-device application market client detects that a new quick fix file is available on the application market server, it downloads the file, and then installs and deploys the file through the bundle manager service in the system.
4. After the quick fix file is deployed, the quick fix engine triggers the application to switch to the quick fix file, ensuring that the user can instantly use the functions where bugs are fixed.
## Quick Fix File Debugging Process
![Quick Fix File Debugging](figures/quick-fix-debug.png)
* As the quick fix capability is not yet available in DevEco Studio, for the time being, you can use the provided command-line tool to develop a quick fix file. The procedure is as follows:
1. With the original application source code and the source code after bug fixes, use the command-line tool to build and create quick fix files in .hpf format. Sign the .hpf files before installing them on the device. As aforementioned, the .appqf file cannot be installed on the device.
2. Install and deploy the .hqf files on the device using the command-line tool.
3. After the .hqf files are deployed, a callback is called to instruct the quick fix engine to trigger the application to switch to the quick fix file, ensuring that the user can instantly use the functions where bugs are fixed.
# Shared Package Overview
OpenHarmony provides two types of shared packages: [Harmony Achive (HAR)](har-package.md) static shared package and Harmony Shared Package (HSP) dynamic shared package.
Both the HAR and HSP are used to share code and resources and can contain code, C++ libraries, resources, and configuration files. The biggest differences between them are as follows: The code and resources in the HAR are compiled with the invoking module, and if there are multiple invoking modules, the build product contains multiple copies of the same code and resources; the code and resources in the HSP can be compiled independently, and the build product contains only one copy of the code and resources.
**Figure 1** HAR and HSP in the App Pack
![in-app-hsp-har](figures/in-app-hsp-har.png)
The HSP is designed to solve the following issues with the HAR:
- When multiple HAPs reference the same HAR, the size of the App Pack swells.
- When multiple HAPs reference the same HAR, some state variables in the HAR cannot be shared.
Restrictions on the HSP:
- The HSP and its invoking modules must be in the stage model.
- The HSP and its invoking modules must use the **esmodule **compilation mode.
- The HSP does not support the declaration of **abilities** and **extensionAbilities** in its configuration file.
The HSP can be classified as [in-application HSP](in-app-hsp.md) or [inter-application HSP](cross-app-hsp.md), depending on the configuration files and usage methods.
# Application Configuration File Overview (Stage Model)
Each application project must have configuration files in its code directory. These configuration files provide basic application information for build tools, operating systems, and application markets.
In the code directory of an application project developed in stage model, there are two types of configuration files: one **app.json5** file and one or more **module.json5** files.
The [app.json5](app-configuration-file.md) file contains the following contents:
- Application-wide configuration, including the bundle name, developer, and version number.
- Device-specific configuration.
The [module.json5](module-configuration-file.md) file contains the following contents:
- Basic module configuration, such as the name, type, description, and supported device types of the module.
- Information about the [application components](../application-models/stage-model-development-overview.md), including the descriptions of the UIAbility and ExtensionAbility components.
- Information about the permissions required during application running.
...@@ -20,7 +20,7 @@ ...@@ -20,7 +20,7 @@
> **NOTE** > **NOTE**
> >
> If you are using DevEco Studio V3.0 Beta3 or later, you can use the [low-code development](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652) mode apart from the traditional coding approach. > If you are using DevEco Studio V3.0 Beta3 or later, you can use the low-code development mode apart from the traditional coding approach.
> >
> On the low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features. > On the low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features.
> >
...@@ -34,7 +34,7 @@ ...@@ -34,7 +34,7 @@
![en-us_image_0000001384652328](figures/en-us_image_0000001384652328.png) ![en-us_image_0000001384652328](figures/en-us_image_0000001384652328.png)
- **entry**: OpenHarmony project module, which can be built into an OpenHarmony Ability Package ([HAP](../../glossary.md#hap)). - **entry**: OpenHarmony project module, which can be built into an OpenHarmony Ability Package ([HAP](../../glossary.md#hap)).
- **src > main > ets**: a collection of eTS source code. - **src > main > ets**: a collection of ArkTS source code.
- **src > main > ets > MainAbility**: entry to your application/service. - **src > main > ets > MainAbility**: entry to your application/service.
- **src > main > ets > MainAbility > pages**: pages contained in **MainAbility**. - **src > main > ets > MainAbility > pages**: pages contained in **MainAbility**.
- **src > main > ets > MainAbility > pages > index.ets**: the first page in the **pages** list, also referred to as the entry to the application. - **src > main > ets > MainAbility > pages > index.ets**: the first page in the **pages** list, also referred to as the entry to the application.
......
...@@ -20,7 +20,7 @@ ...@@ -20,7 +20,7 @@
> **NOTE** > **NOTE**
> >
> You can use the [low-code development](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652) mode apart from the traditional coding approach. > You can use the low-code development mode apart from the traditional coding approach.
> >
> On the low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features. > On the low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features.
> >
...@@ -34,7 +34,7 @@ ...@@ -34,7 +34,7 @@
![en-us_image_0000001364054489](figures/en-us_image_0000001364054489.png) ![en-us_image_0000001364054489](figures/en-us_image_0000001364054489.png)
- **entry**: OpenHarmony project module, which can be built into an OpenHarmony Ability Package ([HAP](../../glossary.md#hap)). - **entry**: OpenHarmony project module, which can be built into an OpenHarmony Ability Package ([HAP](../../glossary.md#hap)).
- **src > main > ets**: a collection of eTS source code. - **src > main > ets**: a collection of ArkTS source code.
- **src > main > ets > entryability**: entry to your application/service. - **src > main > ets > entryability**: entry to your application/service.
- **src > main > ets > pages**: pages included in your application/service. - **src > main > ets > pages**: pages included in your application/service.
- **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Categories and Access](resource-categories-and-access.md#resource-categories). - **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Categories and Access](resource-categories-and-access.md#resource-categories).
......
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
> **NOTE** > **NOTE**
> >
> If you are using DevEco Studio V2.2 Beta1 or later, you can use the [low-code development](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652) mode apart from the traditional coding approach. > If you are using DevEco Studio V2.2 Beta1 or later, you can use the low-code development mode apart from the traditional coding approach.
> >
> On the low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features. > On the low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features.
> >
......
...@@ -187,19 +187,19 @@ ...@@ -187,19 +187,19 @@
- [WebGL](js-apis-webgl.md) - [WebGL](js-apis-webgl.md)
- [WebGL2](js-apis-webgl2.md) - [WebGL2](js-apis-webgl2.md)
- Media - Multimedia
- [@ohos.multimedia.audio (Audio Management)](js-apis-audio.md) - [@ohos.multimedia.audio (Audio Management)](js-apis-audio.md)
- [@ohos.multimedia.avsession (AVSession Management)](js-apis-avsession.md) - [@ohos.multimedia.avsession (AVSession Management)](js-apis-avsession.md)
- [@ohos.multimedia.camera (Camera Management)](js-apis-camera.md) - [@ohos.multimedia.camera (Camera Management)](js-apis-camera.md)
- [@ohos.multimedia.image (Image Processing)](js-apis-image.md) - [@ohos.multimedia.image (Image Processing)](js-apis-image.md)
- [@ohos.multimedia.media (Media)](js-apis-media.md) - [@ohos.multimedia.media (Media)](js-apis-media.md)
- Resource Management - Resource Manager
- [@ohos.i18n (Internationalization)](js-apis-i18n.md) - [@ohos.i18n (Internationalization)](js-apis-i18n.md)
- [@ohos.intl (Internationalization)](js-apis-intl.md) - [@ohos.intl (Internationalization)](js-apis-intl.md)
- [@ohos.resourceManager (Resource Manager)](js-apis-resource-manager.md) - [@ohos.resourceManager (Resource Manager)](js-apis-resource-manager.md)
- Background Tasks - Background Task
- [@ohos.distributedMissionManager (Distributed Mission Management)](js-apis-distributedMissionManager.md) - [@ohos.distributedMissionManager (Distributed Mission Management)](js-apis-distributedMissionManager.md)
- [@ohos.reminderAgentManager (Reminder Agent Management)](js-apis-reminderAgentManager.md) - [@ohos.reminderAgentManager (Reminder Agent Management)](js-apis-reminderAgentManager.md)
- [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](js-apis-resourceschedule-backgroundTaskManager.md) - [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](js-apis-resourceschedule-backgroundTaskManager.md)
...@@ -208,7 +208,7 @@ ...@@ -208,7 +208,7 @@
- [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](js-apis-WorkSchedulerExtensionAbility.md) - [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](js-apis-WorkSchedulerExtensionAbility.md)
- application - application
- [WorkSchedulerExtensionContext](js-apis-inner-application-WorkSchedulerExtensionContext.md) - [WorkSchedulerExtensionContext](js-apis-inner-application-WorkSchedulerExtensionContext.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)
...@@ -217,7 +217,6 @@ ...@@ -217,7 +217,6 @@
- [@ohos.security.huks (HUKS)](js-apis-huks.md) - [@ohos.security.huks (HUKS)](js-apis-huks.md)
- [@ohos.userIAM.faceAuth (Facial Authentication)](js-apis-useriam-faceauth.md) - [@ohos.userIAM.faceAuth (Facial Authentication)](js-apis-useriam-faceauth.md)
- [@ohos.userIAM.userAuth (User Authentication)](js-apis-useriam-userauth.md) - [@ohos.userIAM.userAuth (User Authentication)](js-apis-useriam-userauth.md)
- [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md)
- security - security
- [PermissionRequestResult](js-apis-permissionrequestresult.md) - [PermissionRequestResult](js-apis-permissionrequestresult.md)
...@@ -238,15 +237,16 @@ ...@@ -238,15 +237,16 @@
- [@ohos.file.environment (Directory Environment Capability)](js-apis-file-environment.md) - [@ohos.file.environment (Directory Environment Capability)](js-apis-file-environment.md)
- [@ohos.file.fileAccess (User File Access and Management)](js-apis-fileAccess.md) - [@ohos.file.fileAccess (User File Access and Management)](js-apis-fileAccess.md)
- [@ohos.file.fileExtensionInfo (User File Extension Information)](js-apis-fileExtensionInfo.md) - [@ohos.file.fileExtensionInfo (User File Extension Information)](js-apis-fileExtensionInfo.md)
- [@ohos.file.fileUri (File URI)](js-apis-file-fileUri.md)
- [@ohos.file.fs (File Management)](js-apis-file-fs.md) - [@ohos.file.fs (File Management)](js-apis-file-fs.md)
- [@ohos.file.hash (File Hash Processing)](js-apis-file-hash.md) - [@ohos.file.hash (File Hash Processing)](js-apis-file-hash.md)
- [@ohos.file.picker (Picker)](js-apis-file-picker.md) - [@ohos.file.picker (File Picker)](js-apis-file-picker.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.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.filemanagement.userFileManager (User Data Management)](js-apis-userFileManager.md)
- [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md) - [@ohos.fileShare (File Sharing)](js-apis-fileShare.md)
- Telephony Service - Telephony Service
- [@ohos.contact (Contacts)](js-apis-contact.md) - [@ohos.contact (Contacts)](js-apis-contact.md)
...@@ -276,8 +276,8 @@ ...@@ -276,8 +276,8 @@
- [@ohos.rpc (RPC)](js-apis-rpc.md) - [@ohos.rpc (RPC)](js-apis-rpc.md)
- [@ohos.wifiManager (WLAN)](js-apis-wifiManager.md) - [@ohos.wifiManager (WLAN)](js-apis-wifiManager.md)
- [@ohos.wifiManagerExt (WLAN Extension)](js-apis-wifiManagerExt.md) - [@ohos.wifiManagerExt (WLAN Extension)](js-apis-wifiManagerExt.md)
- [@ohos.wifi (To Be Deprecated)](js-apis-wifi.md) - [@ohos.wifi (To Be Deprecated Soon)](js-apis-wifi.md)
- [@ohos.wifiext (To Be Deprecated)](js-apis-wifiext.md) - [@ohos.wifiext (To Be Deprecated Soon)](js-apis-wifiext.md)
- tag - tag
- [nfctech (Standard NFC Technologies)](js-apis-nfctech.md) - [nfctech (Standard NFC Technologies)](js-apis-nfctech.md)
- [tagSession (Standard NFC Tag Session)](js-apis-tagSession.md) - [tagSession (Standard NFC Tag Session)](js-apis-tagSession.md)
...@@ -318,6 +318,7 @@ ...@@ -318,6 +318,7 @@
- [@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)
- [@ohos.brightness (Screen Brightness)](js-apis-brightness.md) - [@ohos.brightness (Screen Brightness)](js-apis-brightness.md)
- [@ohos.charger (Charging Type)](js-apis-charger.md)
- [@ohos.deviceInfo (Device Information)](js-apis-device-info.md) - [@ohos.deviceInfo (Device Information)](js-apis-device-info.md)
- [@ohos.distributedHardware.deviceManager (Device Management)](js-apis-device-manager.md) - [@ohos.distributedHardware.deviceManager (Device Management)](js-apis-device-manager.md)
- [@ohos.geoLocationManager (Geolocation Manager)](js-apis-geoLocationManager.md) - [@ohos.geoLocationManager (Geolocation Manager)](js-apis-geoLocationManager.md)
...@@ -349,7 +350,7 @@ ...@@ -349,7 +350,7 @@
- [@ohos.account.distributedAccount (Distributed Account Management)](js-apis-distributed-account.md) - [@ohos.account.distributedAccount (Distributed Account Management)](js-apis-distributed-account.md)
- [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md) - [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md)
- Custom Management - Customization
- [@ohos.configPolicy (Configuration Policy)](js-apis-configPolicy.md) - [@ohos.configPolicy (Configuration Policy)](js-apis-configPolicy.md)
- [@ohos.enterprise.accountManager (Account Management)](js-apis-enterprise-accountManager.md) - [@ohos.enterprise.accountManager (Account Management)](js-apis-enterprise-accountManager.md)
- [@ohos.enterprise.adminManager (Enterprise Device Management)](js-apis-enterprise-adminManager.md) - [@ohos.enterprise.adminManager (Enterprise Device Management)](js-apis-enterprise-adminManager.md)
...@@ -403,6 +404,7 @@ ...@@ -403,6 +404,7 @@
- [@ohos.fileio (File Management)](js-apis-fileio.md) - [@ohos.fileio (File Management)](js-apis-fileio.md)
- [@ohos.geolocation (Geolocation)](js-apis-geolocation.md) - [@ohos.geolocation (Geolocation)](js-apis-geolocation.md)
- [@ohos.hiAppEvent (Application Event Logging)](js-apis-hiappevent.md) - [@ohos.hiAppEvent (Application Event Logging)](js-apis-hiappevent.md)
- [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md)
- [@ohos.prompt (Prompt)](js-apis-prompt.md) - [@ohos.prompt (Prompt)](js-apis-prompt.md)
- [@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)
...@@ -414,6 +416,7 @@ ...@@ -414,6 +416,7 @@
- [@system.battery (Battery Information)](js-apis-system-battery.md) - [@system.battery (Battery Information)](js-apis-system-battery.md)
- [@system.bluetooth (Bluetooth)](js-apis-system-bluetooth.md) - [@system.bluetooth (Bluetooth)](js-apis-system-bluetooth.md)
- [@system.brightness (Screen Brightness)](js-apis-system-brightness.md) - [@system.brightness (Screen Brightness)](js-apis-system-brightness.md)
- [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md)
- [@system.configuration (Application Configuration)](js-apis-system-configuration.md) - [@system.configuration (Application Configuration)](js-apis-system-configuration.md)
- [@system.device (Device Information)](js-apis-system-device.md) - [@system.device (Device Information)](js-apis-system-device.md)
- [@system.fetch (Data Request)](js-apis-system-fetch.md) - [@system.fetch (Data Request)](js-apis-system-fetch.md)
......
...@@ -105,3 +105,55 @@ export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbil ...@@ -105,3 +105,55 @@ export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbil
} }
}; };
``` ```
## EnterpriseAdminExtensionAbility.onAppStart<sup>10+</sup>
onAppStart(bundleName: string): void
Called when an application is started.
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**System API**: This is a system API.
**Parameters**
| Parameter | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- |
| bundleName | string | Yes | Bundle name of the application started.|
**Example**
```ts
export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility {
onAppStart(bundleName: string) {
console.log("started bundle name: " + bundleName);
}
};
```
## EnterpriseAdminExtensionAbility.onAppStop<sup>10+</sup>
onAppStop(bundleName: string): void
Called when an application is stopped.
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**System API**: This is a system API.
**Parameters**
| Parameter | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- |
| bundleName | string | Yes | Bundle name of the application stopped.|
**Example**
```ts
export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility {
onAppStop(bundleName: string) {
console.log("stopped bundle name: " + bundleName);
}
};
```
...@@ -504,8 +504,8 @@ For details about the error codes, see [Application Access Control Error Codes]( ...@@ -504,8 +504,8 @@ For details about the error codes, see [Application Access Control Error Codes](
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 12100001 | The parameter is invalid. The tokenID in list is all invalid, or the permissionName in list is all invalid. | | 12100001 | The parameter is invalid. The tokenIDs or permissionNames in the list are all invalid. |
| 12100004 | The API is not used together with "on()". | | 12100004 | The interface is not used together with "on". |
| 12100007 | Service is abnormal. | | 12100007 | Service is abnormal. |
| 12100008 | Out of memory. | | 12100008 | Out of memory. |
...@@ -532,7 +532,9 @@ verifyAccessToken(tokenID: number, permissionName: Permissions): Promise&lt;Gran ...@@ -532,7 +532,9 @@ verifyAccessToken(tokenID: number, permissionName: Permissions): Promise&lt;Gran
Verifies whether a permission is granted to an application. This API uses a promise to return the result. Verifies whether a permission is granted to an application. This API uses a promise to return the result.
> **NOTE**<br>You are advised to use [checkAccessToken](#checkaccesstoken9). > **NOTE**
>
> You are advised to use [checkAccessToken](#checkaccesstoken9).
**System capability**: SystemCapability.Security.AccessToken **System capability**: SystemCapability.Security.AccessToken
...@@ -619,7 +621,7 @@ Requests permissions from the user in a dialog box. This API uses a promise to ...@@ -619,7 +621,7 @@ Requests permissions from the user in a dialog box. This API uses a promise to
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Ability context of the application that requests the permissions. | | context | Context | Yes| Ability context of the application that requests the permissions. |
| permissionList | Array&lt;Permissions&gt; | Yes| Permissions requested. For details about the permissions, see the [Application Permission List](../../security/permission-list.md). | | permissionList | Array&lt;Permissions&gt; | Yes| Permissions requested. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).|
**Return value** **Return value**
...@@ -659,7 +661,9 @@ verifyAccessToken(tokenID: number, permissionName: string): Promise&lt;GrantStat ...@@ -659,7 +661,9 @@ verifyAccessToken(tokenID: number, permissionName: string): Promise&lt;GrantStat
Verifies whether a permission is granted to an application. This API uses a promise to return the result. Verifies whether a permission is granted to an application. This API uses a promise to return the result.
> NOTE<br>This API is deprecated since API version 9. You are advised to use [checkAccessToken](#checkaccesstoken9). > **NOTE**
>
> This API is no longer maintained since API version 9. You are advised to use [checkAccessToken](#checkaccesstoken9).
**System capability**: SystemCapability.Security.AccessToken **System capability**: SystemCapability.Security.AccessToken
......
...@@ -4,7 +4,7 @@ The **appRecovery** module provides APIs for recovering faulty applications. ...@@ -4,7 +4,7 @@ The **appRecovery** module provides APIs for recovering faulty applications.
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. In the current version, only applications with a single ability in a single process can be recovered. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. In API version 9, only applications with a single ability in a process can be recovered. In API version 10, applications with multiple abilities in a process can be recovered.
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -51,7 +51,7 @@ Enumerates the application state saving modes. This enum is used as an input par ...@@ -51,7 +51,7 @@ Enumerates the application state saving modes. This enum is used as an input par
enableAppRecovery(restart?: [RestartFlag](#apprecoveryrestartflag), saveOccasion?: [SaveOccasionFlag](#apprecoverysaveoccasionflag), saveMode?: [SaveModeFlag](#apprecoverysavemodeflag)) : void; enableAppRecovery(restart?: [RestartFlag](#apprecoveryrestartflag), saveOccasion?: [SaveOccasionFlag](#apprecoverysaveoccasionflag), saveMode?: [SaveModeFlag](#apprecoverysavemodeflag)) : void;
Enables application recovery. Enables application recovery. After this API is called, the first ability that is displayed when the application is started from the initiator can be restored.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -63,8 +63,8 @@ Enables application recovery. ...@@ -63,8 +63,8 @@ Enables application recovery.
| saveOccasion | [SaveOccasionFlag](#apprecoverysaveoccasionflag) | No| Scenario for saving the application state. By default, the state is saved when a fault occurs.| | saveOccasion | [SaveOccasionFlag](#apprecoverysaveoccasionflag) | No| Scenario for saving the application state. By default, the state is saved when a fault occurs.|
| saveMode | [SaveModeFlag](#apprecoverysavemodeflag) | No| Application state saving mode. By default, the application state is written to the local file cache.| | saveMode | [SaveModeFlag](#apprecoverysavemodeflag) | No| Application state saving mode. By default, the application state is written to the local file cache.|
**Example** **Example**
```ts ```ts
import appRecovery from '@ohos.app.ability.appRecovery'; import appRecovery from '@ohos.app.ability.appRecovery';
import AbilityStage from '@ohos.app.ability.AbilityStage'; import AbilityStage from '@ohos.app.ability.AbilityStage';
...@@ -84,13 +84,22 @@ export default class MyAbilityStage extends AbilityStage { ...@@ -84,13 +84,22 @@ export default class MyAbilityStage extends AbilityStage {
restartApp(): void; restartApp(): void;
Restarts the application. This API can be used together with APIs of [errorManager](js-apis-app-ability-errorManager.md). Restarts the current process and starts the first ability that is displayed when the application is started. If the state of this ability is saved, the saved state data is passed into the **wantParam** attribute in the **want** parameter of the **OnCreate** lifecycle callback of the ability.
In API version 10, the ability specified by [setRestartWant](#apprecoverysetrestartwant) is started. If no ability is specified, the following rules are used:
- If the ability of the current application running in the foreground supports recovery, that ability is started.
- If multiple abilities that support recovery is running in the foreground, only the last ability is started.
- If no ability is running in the foreground, none of them is started.
This API can be used together with the APIs of [errorManager](js-apis-app-ability-errorManager.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Example**
**Example**
```ts ```ts
import appRecovery from '@ohos.app.ability.appRecovery'; import appRecovery from '@ohos.app.ability.appRecovery';
import errorManager from '@ohos.app.ability.errorManager'; import errorManager from '@ohos.app.ability.errorManager';
...@@ -113,7 +122,7 @@ try { ...@@ -113,7 +122,7 @@ try {
saveAppState(): boolean; saveAppState(): boolean;
Saves the application state. This API can be used together with APIs of [errorManager](js-apis-app-ability-errorManager.md). Saves the application state. This API can be used together with the APIs of [errorManager](js-apis-app-ability-errorManager.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -123,8 +132,8 @@ Saves the application state. This API can be used together with APIs of [errorMa ...@@ -123,8 +132,8 @@ Saves the application state. This API can be used together with APIs of [errorMa
| -------- | -------- | | -------- | -------- |
| boolean | Whether the application state is saved. The value **true** is returned if the application state is saved, and **false** is returned otherwise.| | boolean | Whether the application state is saved. The value **true** is returned if the application state is saved, and **false** is returned otherwise.|
**Example** **Example**
```ts ```ts
import appRecovery from '@ohos.app.ability.appRecovery'; import appRecovery from '@ohos.app.ability.appRecovery';
import errorManager from '@ohos.app.ability.errorManager'; import errorManager from '@ohos.app.ability.errorManager';
...@@ -142,3 +151,53 @@ try { ...@@ -142,3 +151,53 @@ try {
console.error('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
``` ```
## appRecovery.saveAppState<sup>10+</sup>
saveAppState(context?: UIAbilityContext): boolean;
Saves the ability state, which will be used for recovery. This API can be used together with the APIs of [errorManager](js-apis-app-ability-errorManager.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Whether the application state is saved. The value **true** is returned if the application state is saved, and **false** is returned otherwise.|
**Example**
```ts
import appRecovery from '@ohos.app.ability.appRecovery';
onBackground() {
hilog.info(0x0000, '[demo]', '%{public}s', 'EntryAbility onBackground');
appRecovery.saveAppState(this.context)
}
```
## appRecovery.setRestartWant<sup>10+</sup>
setRestartWant(want: Want): void;
Sets an ability that will be recovered. The ability must be a UIAbility in the current bundle.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Example**
```ts
import appRecovery from '@ohos.app.ability.appRecovery';
Button ("Start to Recover Ability")
.fontSize(40)
.fontWeight(FontWeight.Bold)
.onClick(()=> {
// set restart want
let want = {
bundleName: "ohos.samples.recovery",
abilityName: "RecoveryAbility"
};
appRecovery.setRestartWant(want);
})
```
...@@ -290,7 +290,7 @@ Obtains the information about a given mission. This API uses an asynchronous cal ...@@ -290,7 +290,7 @@ Obtains the information about a given mission. This API uses an asynchronous cal
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| deviceId | string | Yes| Device ID. It is a null string by default for the local device.| | deviceId | string | Yes| Device ID. It is a null string by default for the local device.|
| missionId | number | Yes| Mission ID.| | missionId | number | Yes| Mission ID.|
| callback | AsyncCallback&lt;[MissionInfo](./js-apis-inner-application-missionInfo.md))&gt; | Yes| Callback used to return the mission information obtained.| | callback | AsyncCallback&lt;[MissionInfo](./js-apis-inner-application-missionInfo.md)&gt; | Yes| Callback used to return the mission information obtained.|
**Example** **Example**
......
...@@ -319,7 +319,7 @@ Sends sequenceable data to the target ability. ...@@ -319,7 +319,7 @@ Sends sequenceable data to the target ability.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.|
| data | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Yes| Sequenceable data. You need to customize the data.| | data | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Yes| Parcelable data. You need to customize the data.|
**Return value** **Return value**
...@@ -338,7 +338,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -338,7 +338,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
**Example** **Example**
```ts ```ts
class MyMessageAble{ // Custom sequenceable data structure. class MyMessageAble{ // Custom parcelable data structure.
name:'' name:''
str:'' str:''
num: 1 num: 1
...@@ -346,15 +346,15 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -346,15 +346,15 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
this.name = name; this.name = name;
this.str = str; this.str = str;
} }
marshalling(messageParcel) { marshalling(messageSequence) {
messageParcel.writeInt(this.num); messageSequence.writeInt(this.num);
messageParcel.writeString(this.str); messageSequence.writeString(this.str);
console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]'); console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]');
return true; return true;
} }
unmarshalling(messageParcel) { unmarshalling(messageSequence) {
this.num = messageParcel.readInt(); this.num = messageSequence.readInt();
this.str = messageParcel.readString(); this.str = messageSequence.readString();
console.log('MyMessageAble unmarshalling num[${this.num}] str[${this.str}]'); console.log('MyMessageAble unmarshalling num[${this.num}] str[${this.str}]');
return true; return true;
} }
...@@ -369,7 +369,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -369,7 +369,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
deviceId: '' deviceId: ''
}).then((obj) => { }).then((obj) => {
caller = obj; caller = obj;
let msg = new MyMessageAble('msg', 'world'); // See the definition of Sequenceable. let msg = new MyMessageAble('msg', 'world'); // See the definition of Parcelable.
caller.call(method, msg) caller.call(method, msg)
.then(() => { .then(() => {
console.log('Caller call() called'); console.log('Caller call() called');
...@@ -387,7 +387,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -387,7 +387,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
## Caller.callWithResult ## Caller.callWithResult
callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageParcel&gt;; callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageSequence&gt;;
Sends sequenceable data to the target ability and obtains the sequenceable data returned by the target ability. Sends sequenceable data to the target ability and obtains the sequenceable data returned by the target ability.
...@@ -398,13 +398,13 @@ Sends sequenceable data to the target ability and obtains the sequenceable data ...@@ -398,13 +398,13 @@ Sends sequenceable data to the target ability and obtains the sequenceable data
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.|
| data | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Yes| Sequenceable data. You need to customize the data.| | data | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Yes| Parcelable data. You need to customize the data.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[rpc.MessageParcel](js-apis-rpc.md#sequenceabledeprecated)&gt; | Promise used to return the sequenceable data from the target ability.| | Promise&lt;[rpc.MessageSequence](js-apis-rpc.md#messagesequence9)&gt; | Promise used to return the sequenceable data from the target ability.|
**Error codes** **Error codes**
...@@ -425,15 +425,15 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -425,15 +425,15 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
this.name = name; this.name = name;
this.str = str; this.str = str;
} }
marshalling(messageParcel) { marshalling(messageSequence) {
messageParcel.writeInt(this.num); messageSequence.writeInt(this.num);
messageParcel.writeString(this.str); messageSequence.writeString(this.str);
console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]'); console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]');
return true; return true;
} }
unmarshalling(messageParcel) { unmarshalling(messageSequence) {
this.num = messageParcel.readInt(); this.num = messageSequence.readInt();
this.str = messageParcel.readString(); this.str = messageSequence.readString();
console.log('MyMessageAble unmarshalling num[${this.num] str[${this.str}]'); console.log('MyMessageAble unmarshalling num[${this.num] str[${this.str}]');
return true; return true;
} }
...@@ -453,7 +453,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -453,7 +453,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
.then((data) => { .then((data) => {
console.log('Caller callWithResult() called'); console.log('Caller callWithResult() called');
let retmsg = new MyMessageAble(0, ''); let retmsg = new MyMessageAble(0, '');
data.readSequenceable(retmsg); data.readParcelable(retmsg);
}) })
.catch((callErr) => { .catch((callErr) => {
console.log('Caller.callWithResult catch error, error.code: ${JSON.stringify(callErr.code)}, error.message: ${JSON.stringify(callErr.message)}'); console.log('Caller.callWithResult catch error, error.code: ${JSON.stringify(callErr.code)}, error.message: ${JSON.stringify(callErr.message)}');
...@@ -712,7 +712,7 @@ Registers a caller notification callback, which is invoked when the target abili ...@@ -712,7 +712,7 @@ Registers a caller notification callback, which is invoked when the target abili
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities.| | method | string | Yes| Notification message string negotiated between the two abilities.|
| callback | [CalleeCallback](#calleecallback) | Yes| JS notification synchronization callback of the [rpc.MessageParcel](js-apis-rpc.md#messageparceldeprecated) type. The callback must return at least one empty [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) object. Otherwise, the function execution fails.| | callback | [CalleeCallback](#calleecallback) | Yes| JS notification synchronization callback of the [rpc.MessageSequence](js-apis-rpc.md#messagesequence9) type. The callback must return at least one empty [rpc.Parcelable](js-apis-rpc.md#parcelable9) object. Otherwise, the function execution fails.|
**Error codes** **Error codes**
...@@ -733,15 +733,15 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -733,15 +733,15 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
this.name = name; this.name = name;
this.str = str; this.str = str;
} }
marshalling(messageParcel) { marshalling(messageSequence) {
messageParcel.writeInt(this.num); messageSequence.writeInt(this.num);
messageParcel.writeString(this.str); messageSequence.writeString(this.str);
console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]'); console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]');
return true; return true;
} }
unmarshalling(messageParcel) { unmarshalling(messageSequence) {
this.num = messageParcel.readInt(); this.num = messageSequence.readInt();
this.str = messageParcel.readString(); this.str = messageSequence.readString();
console.log('MyMessageAble unmarshalling num[${this.num}] str[${this.str}]'); console.log('MyMessageAble unmarshalling num[${this.num}] str[${this.str}]');
return true; return true;
} }
...@@ -750,7 +750,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -750,7 +750,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
function funcCallBack(pdata) { function funcCallBack(pdata) {
console.log('Callee funcCallBack is called ${pdata}'); console.log('Callee funcCallBack is called ${pdata}');
let msg = new MyMessageAble('test', ''); let msg = new MyMessageAble('test', '');
pdata.readSequenceable(msg); pdata.readParcelable(msg);
return new MyMessageAble('test1', 'Callee test'); return new MyMessageAble('test1', 'Callee test');
} }
export default class MainUIAbility extends UIAbility { export default class MainUIAbility extends UIAbility {
...@@ -816,10 +816,10 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -816,10 +816,10 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
## CalleeCallback ## CalleeCallback
(indata: rpc.MessageParcel): rpc.Parcelable; (indata: rpc.MessageSequence): rpc.Parcelable;
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
| Name| Readable| Writable| Type| Description| | Name| Readable| Writable| Type| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| (indata: [rpc.MessageParcel](js-apis-rpc.md#sequenceabledeprecated)) | Yes| No| [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Prototype of the listener function registered by the callee.| | (indata: [rpc.MessageSequence](js-apis-rpc.md#messagesequence9)) | Yes| No| [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Prototype of the listener function registered by the callee.|
...@@ -47,7 +47,7 @@ Enumerates the widget types. ...@@ -47,7 +47,7 @@ Enumerates the widget types.
| Name | Value | Description | | Name | Value | Description |
| ----------- | ---- | ------------ | | ----------- | ---- | ------------ |
| JS | 1 | JS widget. | | JS | 1 | JS widget. |
| eTS | 2 | eTS widget.| | eTS | 2 | ArkTS widget.|
## ColorMode ## ColorMode
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册