提交 e55ae2ca 编写于 作者: C chensi10

Merge remote-tracking branch 'upstream/master'

...@@ -435,6 +435,7 @@ zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @cheng_guohong ...@@ -435,6 +435,7 @@ zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @cheng_guohong
zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208
zh-cn/application-dev/reference/apis/js-apis-system-cipher.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-system-cipher.md @gaoyong @zengyawen @niejiteng @jumozhanjiang
zh-cn/application-dev/reference/apis/js-apis-system-configuration.md @Buda-Liu @ningningW @budda-wang @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-configuration.md @Buda-Liu @ningningW @budda-wang @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-system-date-time.md @feng-aiwen @ningningW @illybyy @murphy1984
zh-cn/application-dev/reference/apis/js-apis-system-device.md @mupceet @zengyawen @handyohos @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-system-device.md @mupceet @zengyawen @handyohos @nan-xiansen
zh-cn/application-dev/reference/apis/js-apis-system-fetch.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-system-fetch.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-system-file.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-system-file.md @panqinxu @zengyawen @bubble_mao @jinhaihw
...@@ -520,7 +521,7 @@ zh-cn/application-dev/reference/apis/js-apis-bundleManager.md @shuaytao @RayShih ...@@ -520,7 +521,7 @@ zh-cn/application-dev/reference/apis/js-apis-bundleManager.md @shuaytao @RayShih
zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md @jayleehw @RayShih @li-weifeng2 @currydavids zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md @jayleehw @RayShih @li-weifeng2 @currydavids
zh-cn/application-dev/reference/apis/js-apis-configPolicy.md @Buda-Liu @ningningW @budda-wang @yangqing3 zh-cn/application-dev/reference/apis/js-apis-configPolicy.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-cooperate.md @yuanxinying @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-cooperate.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @gaoyong @zengyawen @niejiteng @jumozhanjiang
zh-cn/application-dev/reference/apis/js-apis-cert.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-cert.md @gaoyong @zengyawen @niejiteng @jumozhanjiang
...@@ -528,8 +529,13 @@ zh-cn/application-dev/reference/apis/js-apis-curve.md @huaweimaxuchu @HelloCreas ...@@ -528,8 +529,13 @@ zh-cn/application-dev/reference/apis/js-apis-curve.md @huaweimaxuchu @HelloCreas
zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-distributedBundle.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-distributedBundle.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md @Buda-Liu @ningningW @budda-wang @yangqing3 zh-cn/application-dev/reference/apis/js-apis-enterprise-accountManager.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md @Buda-Liu @ningningW @budda-wang @yangqing3 zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceControl.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-networkManager.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-wifiManager.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-freeInstall.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-freeInstall.md @shuaytao @RayShih @wangzhen107 @inter515
......
...@@ -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)
......
...@@ -250,9 +250,9 @@ In the stage model, in the onWindowStageCreate lifecycle of an ability, you can ...@@ -250,9 +250,9 @@ In the stage model, in the onWindowStageCreate lifecycle of an ability, you can
Use the API described in the table below to obtain the context associated with an ArkTS page. Use the API described in the table below to obtain the context associated with an ArkTS page.
| API | Description | | API | Description |
| :------------------------------------ | :--------------------------- | | :------------------------------------ | :----------------------------------------------------------- |
| getContext(component: Object): Object | Obtains the **Context** object associated with a component on the page.| | getContext(component: Object): Object | Obtains the **Context** object associated with a component on the page.<br>Since API version 9, this API is supported in ArkTS widgets.|
**Example** **Example**
......
...@@ -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,9 +17,12 @@ ...@@ -17,9 +17,12 @@
- ExtensionAbility Component - ExtensionAbility Component
- [ExtensionAbility Component Overview](extensionability-overview.md) - [ExtensionAbility Component Overview](extensionability-overview.md)
- [ServiceExtensionAbility](serviceextensionability.md) - [ServiceExtensionAbility](serviceextensionability.md)
- [DataShareExtensionAbility](datashareextensionability.md) - [DataShareExtensionAbility (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)
- [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md)
- [InputMethodExtensionAbility](inputmethodextentionability.md)
- [WindowExtensionAbility](windowextensionability.md)
- [AbilityStage Component Container](abilitystage.md) - [AbilityStage Component Container](abilitystage.md)
- [Context](application-context-stage.md) - [Context](application-context-stage.md)
- Want - Want
...@@ -32,15 +35,19 @@ ...@@ -32,15 +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](hop-cross-device-migration.md) - [Cross-Device Migration (for System Applications Only)](hop-cross-device-migration.md)
- [Multi-device Collaboration](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)
- 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)
...@@ -50,6 +57,7 @@ ...@@ -50,6 +57,7 @@
- [Mission Management Scenarios](mission-management-overview.md) - [Mission Management Scenarios](mission-management-overview.md)
- [Mission Management and Launch Type](mission-management-launch-type.md) - [Mission Management and Launch Type](mission-management-launch-type.md)
- [Page Stack and MissionList](page-mission-stack.md) - [Page Stack and MissionList](page-mission-stack.md)
- [Setting the Icon and Name of a Mission Snapshot](mission-set-icon-name-for-task-snapshot.md)
- [Application Configuration File](config-file-stage.md) - [Application Configuration File](config-file-stage.md)
- FA Model Development - FA Model Development
- [FA Model Development Overview](fa-model-development-overview.md) - [FA Model Development Overview](fa-model-development-overview.md)
...@@ -63,7 +71,7 @@ ...@@ -63,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](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)
......
# Using Explicit Want to Start an Ability # Using Explicit Want to Start an Ability
When a user touches a button in an application, the application often needs to start a UIAbility component to complete a specific task. If the **abilityName** and **bundleName** parameters are specified when starting a UIAbility, then the explicit Want is used.
When a user touches a button in an application, the application often needs to start a UIAbility component to complete a specific task. If the **abilityName** and **bundleName** parameters are specified when starting a UIAbility, the explicit Want is used. For details about how to use the explicit Want, see [Starting UIAbility in the Same Application](uiability-intra-device-interaction.md#starting-uiability-in-the-same-application). ## Using Explicit Want
The user touches a button in the application to start the UIAbility component to complete a specific task. To start the UIAbility component in explicit Want mode, the **abilityName** and **bundleName** parameters must be specified. For details, see [Starting UIAbility in the Same Application](uiability-intra-device-interaction.md#starting-uiability-in-the-same-application).
# Using Implicit Want to Open a Website # Using Implicit Want to Open a Website
This section uses the operation of using a browser to open a website as an example. It is assumed that one or more browser applications are installed on the device. To ensure that the browser application can work properly, configure the [module.json5 file](../quick-start/module-configuration-file.md) as follows:
## Prerequisites
One or more browsers are installed on your device.
The **module.json5** of a browser application is as follows:
```json ```json
"skills": [ {
{ "module": {
"entities": [ // ...
"entity.system.browsable" "abilities": [
// ...
],
"actions": [
"ohos.want.action.viewData"
// ...
],
"uris": [
{
"scheme": "https",
"host": "www.test.com",
"port": "8080",
// Prefix matching is used.
"pathStartWith": "query",
"type": "text/*"
},
{ {
"scheme": "http",
// ... // ...
"skills": [
{
"entities": [
"entity.system.home",
"entity.system.browsable"
// ...
],
"actions": [
"action.system.home",
"ohos.want.action.viewData"
// ...
],
"uris": [
{
"scheme": "https",
"host": "www.test.com",
"port": "8080",
// Prefix matching is used.
"pathStartWith": "query",
"type": "text/*"
},
{
"scheme": "http",
// ...
}
// ...
]
}
]
} }
// ...
] ]
}, }
] }
``` ```
In the initiator UIAbility, use implicit Want to start the browser application.
## How to Develop ```ts
import common from '@ohos.app.ability.common';
1. Use the custom function **implicitStartAbility** to start an ability. function implicitStartAbility() {
let context = getContext(this) as common.UIAbilityContext;
```ts let wantInfo = {
async implicitStartAbility() { // Uncomment the line below if you want to implicitly query data only in the specific bundle.
try { // bundleName: "com.example.myapplication",
let want = { "action": "ohos.want.action.viewData",
// Uncomment the line below if you want to implicitly query data only in the specific bundle. // entities can be omitted.
// bundleName: "com.example.myapplication", "entities": ["entity.system.browsable"],
"action": "ohos.want.action.viewData", "uri": "https://www.test.com:8080/query/student",
// entities can be omitted. "type": "text/plain"
"entities": [ "entity.system.browsable" ], }
"uri": "https://www.test.com:8080/query/student", context.startAbility(wantInfo).then(() => {
"type": "text/plain" // ...
} }).catch((err) => {
let context = getContext(this) as common.UIAbilityContext; // ...
await context.startAbility(want) })
console.info(`explicit start ability succeed`) }
} catch (error) { ```
console.info(`explicit start ability failed with ${error.code}`)
}
}
```
The matching process is as follows:
1. If **action** in the passed **want** parameter is specified and is included in **actions** under **skills**, the matching is successful.
2. If **entities** in the passed **want** parameter is specified and is included in **entities** under **skills**, the matching is successful.
3. If **uri** in the passed **want** parameter is included in **uris** under **skills**, which is concatenated into `https://www.test.com:8080/query*` (where \* is a wildcard), the matching is successful. The matching process is as follows:
4. If **type** in the passed **want** parameter is specified and is included in **type** under **skills**, the matching is successful. 1. If **action** in the passed **want** parameter is specified and is included in **actions** under **skills** of the ability to match, the matching is successful.
2. If **entities** in the passed **want** parameter is specified and is included in **entities** under **skills** of the ability to match, the matching is successful.
3. If **uri** in the passed **want** parameter is included in **uris** under **skills** of the ability to match, which is concatenated into https://www.test.com:8080/query* (where * is a wildcard), the matching is successful.
4. If **type** in the passed **want** parameter is specified and is included in **type** under **skills** of the ability to match, the matching is successful.
2. When there are multiple matching applications, a dialog box is displayed for you to select one of them. When there are multiple matching applications, a dialog box is displayed for you to select one of them. The following figure shows an example.
![stage-want1](figures/stage-want1.png) ![](figures/ability-startup-with-implicit-want1.png)
\ No newline at end of file
...@@ -29,6 +29,18 @@ AbilityStage is not automatically generated in the default project of DevEco Stu ...@@ -29,6 +29,18 @@ AbilityStage is not automatically generated in the default project of DevEco Stu
} }
} }
``` ```
4. Set **srcEntry** in the [module.json5 file](../quick-start/module-configuration-file.md) to the code path of the module.
```json
{
"module": {
"name": "entry",
"type": "entry",
"srcEntry": "./ets/myabilitystage/MyAbilityStage.ts",
// ...
}
}
```
[AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) has the lifecycle callback [onCreate()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageoncreate) and the event callbacks [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant), [onConfigurationUpdated()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonconfigurationupdate), and [onMemoryLevel()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonmemorylevel). [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) has the lifecycle callback [onCreate()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageoncreate) and the event callbacks [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant), [onConfigurationUpdated()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonconfigurationupdate), and [onMemoryLevel()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonmemorylevel).
...@@ -41,6 +53,7 @@ AbilityStage is not automatically generated in the default project of DevEco Stu ...@@ -41,6 +53,7 @@ AbilityStage is not automatically generated in the default project of DevEco Stu
- **onConfigurationUpdated()** event callback: triggered when the global system configuration changes. The global system configuration, such as the system language and theme, are defined in the [Configuration](../reference/apis/js-apis-app-ability-configuration.md) class before project configuration. - **onConfigurationUpdated()** event callback: triggered when the global system configuration changes. The global system configuration, such as the system language and theme, are defined in the [Configuration](../reference/apis/js-apis-app-ability-configuration.md) class before project configuration.
- **onMemoryLevel()** event callback: triggered when the system adjusts the memory. - **onMemoryLevel()** event callback: triggered when the system adjusts the memory.
When an application is switched to the background, it is cached in the background. This adversely affects the overall system performance. When system resources are insufficient, the system reclaims memory from applications in multiple ways. For example, the system may stop applications to release memory for executing key tasks. To further maintain the balance of the system memory and prevent the system from stopping application processes, you can subscribe to the system memory changes in the **onMemoryLevel()** lifecycle callback of AbilityStage to release unnecessary resources. When an application is switched to the background, it is cached in the background. This adversely affects the overall system performance. When system resources are insufficient, the system reclaims memory from applications in multiple ways. For example, the system may stop applications to release memory for executing key tasks. To further maintain the balance of the system memory and prevent the system from stopping application processes, you can subscribe to the system memory changes in the **onMemoryLevel()** lifecycle callback of AbilityStage to release unnecessary resources.
...@@ -54,4 +67,3 @@ When an application is switched to the background, it is cached in the backgroun ...@@ -54,4 +67,3 @@ When an application is switched to the background, it is cached in the backgroun
} }
} }
``` ```
...@@ -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) {
......
# Using Want to Share Data Between Applications # Using Want to Share Data Between Applications
Users often need to share data (such as a text or an image) from one application to another. The following uses PDF file sharing as an example to describe how to use Want to share data between applications. Users often need to share data (such as a text or an image) from one application to another. The following uses PDF file sharing as an example to describe how to use Want to share data between applications.
Data sharing requires two UIAbility components (one for the sharing party and the other for the shared party) and one system component (used as the application selector). When the sharing party initiates data sharing by calling **startAbility()**, the system implicitly matches and displays all applications that support the type of data to share. After the user selects an application, the system starts the application to complete data sharing.
## Prerequisites In this section, data sharing is triggered by touching a button. You can use other ways to trigger data sharing during application development. This section focuses on how to configure Want to implement data sharing.
1. There are two UIAbility components (one for the sharing party and the other for the shared party) and one system component (used as the application selector). When the sharing party initiates data sharing through **startAbility()**, the application selector is started. The system implicitly matches and displays all applications that support the type of data to share. After the user selects an application, the system starts that application to complete data sharing. The following actions are involved for data sharing:
2. In this section, data sharing is triggered by touching a button. You can use other ways to trigger data sharing during application development. This section focuses on the Want configuration used for data sharing. - **ohos.want.action.select**: action of starting the application selector.
- **ohos.want.action.sendData**: action of sending a single data record, that is, transferring data to the shared party.
3. The following actions are involved in this section:
- **ACTION_SELECT (ohos.want.action.select)**: action of displaying the application selector. ## Sharing Party
- **ACTION_SEND_DATA (ohos.want.action.sendData)**: action of launching the UI for sending a single data record. It is used to transfer data to the shared party.
The sharing party starts an application selector and transfers the data to the shared party. Therefore, Want of the sharing party must be nested at two layers. In the first layer, implicit Want is used together with the **ohos.want.action.select** action to display the application selector. In the second layer, the data to share is declared
## How to Develop in the custom field **parameters**, and then the Want that includes the **ohos.want.action.sendData** action and the **parameters** field is transferred to the application selector. The shared party obtains the shared data from **parameters**.
- Sharing party ```ts
1. In the stage mode, the [File Descriptor (FD)](../reference/apis/js-apis-fileio.md#fileioopensync) is used for file transfer. This example assumes that the path of the file to share is obtained. import common from '@ohos.app.ability.common';
```ts let fileType = 'application/pdf';
import fileIO from '@ohos.fileio'; let fileName = 'TestFile.pdf';
let fileFd = -1; // Obtain the file descriptor (FD) of the file to share.
// let path = ... let fileSize; // Obtain the size of the file to share.
// Open the file whose path is a variable.
let fileFd = fileIO.openSync(path, 0o102, 0o666); function implicitStartAbility() {
``` let context = getContext(this) as common.UIAbilityContext;
let wantInfo = {
2. As described in the prerequisites, the sharing party starts an application selector and shares the data to the selector, and the selector transfers the data to the shared party. Want of the sharing party must be nested at two layers. At the first layer, implicit Want is used together with the **ohos.want.action.select** action to display the application selector. At the second layer, complete Want is declared in the custom field **parameters** to transfer the data to share. / This action is used to implicitly match the application selector.
action: 'ohos.want.action.select',
```ts // This is the custom parameter in the first layer of Want,
import wantConstant from '@ohos.app.ability.wantConstant'; / which is intended to add information to the application selector.
parameters: {
// let path = ... // MIME type of PDF.
// let fileFd = ... "ability.picker.type": fileType,
// let fileSize = ... "ability.picker.fileNames": [fileName],
let want = { "ability.picker.fileSizes": [fileSize],
/ This action is used to implicitly match the application selector. // This is nested Want ,which will be directly sent to the selected application.
action: wantConstant.Action.ACTION_SELECT, "ability.want.params.INTENT": {
// This is the custom parameter in the first layer of Want, "action": "ohos.want.action.sendData",
/ which is intended to add information to the application selector. "type": "application/pdf",
parameters: { "parameters": {
// MIME type of PDF. "keyFd": { "type": "FD", "value": fileFd }
"ability.picker.type": "application/pdf", }
"ability.picker.fileNames": [path],
"ability.picker.fileSizes": [fileSize],
// This nested Want ,which will be directly sent to the selected application.
"ability.want.params.INTENT": {
"action": "ohos.want.action.sendData",
"type": "application/pdf",
"parameters": {
"keyFd": {"type": "FD", "value": fileFd}
}
}
}
} }
``` }
}
In the preceding code, the custom field **parameters** is used. The **ability.picker.\*** fields in the first-layer **parameters** are used to pass the information to be displayed on the application selector. The following fields are involved: context.startAbility(wantInfo).then(() => {
// ...
- **"ability.picker.type"**: The application selector renders the file type icon based on this field. }).catch((err) => {
- **"ability.picker.fileNames"**: The application selector displays the file name based on this field. // ...
- **"ability.picker.fileSizes"**: The application selector displays the file size based on this field. The unit is byte. })
- **"ability.picker.fileNames"** and **"ability.picker.fileSizes"** are arrays and have a one-to-one mapping. }
```
For example, when **"ability.picker.type"** is **"application/pdf"**, **"ability.picker.fileNames"** is **"["APIs.pdf"]"**, and **"ability.picker.fileSizes"** is **"[350 \* 1024]"**, the application selector is displayed as follows:
> **NOTE**
![stage-want2](figures/stage-want2.png) >
> Data sharing can be implemented only in FD format. For details about how to obtain the FD and file name, see [File Management](../reference/apis/js-apis-file-fs.md).
In the preceding code, the **ability.want.params.INTENT** field is nested Want. In this field, **action** and **type** are used for implicit matching by the application selector. For details about implicit matching, see [Matching Rules of Implicit Want](explicit-implicit-want-mappings.md#matching-rules-of-implicit-want). After the user selects an application, the nested Want of the **ability.want.params.INTENT** field is passed to that application.
In the preceding code, under the custom field **parameters**, the following **ability.picker.*** fields are used to pass the information to be displayed on the application selector:
- Shared party
1. As mentioned above, the application selector performs implicit matching based on the **ability.want.params.INTENT** field. Therefore, you must set **skills** in the ability configuration file (**module.json5** file in the stage model) of the shared party as follows: - **ability.picker.type**: file type icon.
- **ability.picker.fileNames**: file name.
```ts - **ability.picker.fileSizes**: file size, in bytes.
"skills": [ - **ability.picker.fileNames** and **ability.picker.fileSizes** are arrays and have a one-to-one mapping.
{
"entities": [ The following figure shows an example.
![](figures/ability-startup-with-implicit-want2.png)
## Shared Party
To enable the shared party to identify the shared content, configure **skills** in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility of the shared party. The **actions** and **type** fields in **uris** match the **action** and **type** fields in **ability.want.params.INTENT** of the sharing party, respectively.
```json
{
"module": {
// ...
"abilities": [
{
// ...
"skills": [
{
// ... // ...
], "actions": [
"actions": [ "action.system.home",
"ohos.want.action.sendData" "ohos.want.action.sendData"
// ... // ...
], ],
"uris": [ "uris": [
{ {
"type": "application/pdf" "type": "application/pdf"
}, },
// ... ]
] }
}, ]
]
```
The **actions** and **type** fields in **uris** match the **action** and **type** fields in **ability.want.params.INTENT**, respectively.
Files can be transferred in FD mode, but not URI mode. In implicit matching, the **type** field in Want must match the **type** field in **uris** under **skills** of the shared party. Therefore, specify only the **type** field in **uris**. If **host** and **port** are specified, the matching fails. The application selector initiates implicit matching based on **ability.want.params.INTENT**. Therefore, when the **uri** field added to **ability.want.params.INTENT** matches the **uris** field under **skills**, the matching is successful and additional data can be transferred.
2. After the application selector starts the shared party, the system calls **onCreate** and passes **ability.want.params.INTENT** to the **want** parameter.
```ts
onCreate(want, launchParam) {
// When keyFd is undefined, the application crashes.
if (want["parameters"]["keyFd"] !== undefined) {
// Receive the file descriptor.
let fd = want["parameters"]["keyFd"].value;
// ...
}
} }
``` ]
}
}
```
After the user selects an application, the Want nested in the **ability.want.params.INTENT** field is passed to that application. The UIAbility of the shared party, after being started, can call [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) to obtain the passed Want.
The following is an example of the Want obtained. You can use the FD of the shared file to perform required operations.
```json
{
"deviceId": "",
"bundleName": "com.example.myapplication",
"abilityName": "EntryAbility",
"moduleName": "entry",
"uri": "",
"type": "application/pdf",
"flags": 0,
"action": "ohos.want.action.sendData",
"parameters": {
"component.startup.newRules": true,
"keyFd": {
"type": "FD",
"value": 36
},
"mime-type": "application/pdf",
"moduleName": "entry",
"ohos.aafwk.param.callerPid": 3488,
"ohos.aafwk.param.callerToken": 537379209,
"ohos.aafwk.param.callerUid": 20010014
},
"entities": []
}
```
# DataShareExtensionAbility # DataShareExtensionAbility (for System Applications Only)
DataShareExtensionAbility is available only for system application. It provides the data sharing capability. System applications can implement a DataShareExtensionAbility or access an existing DataShareExtensionAbility in the system. Third-party applications can only access an existing DataShareExtensionAbility. For details, see [DataShare Development](../database/database-datashare-guidelines.md). DataShareExtensionAbility provides the data sharing capability. System applications can implement a DataShareExtensionAbility or access an existing DataShareExtensionAbility in the system. Third-party applications can only access an existing DataShareExtensionAbility. For details, see [DataShare Development](../database/database-datashare-guidelines.md).
...@@ -9,7 +9,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab ...@@ -9,7 +9,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab
- [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md): ExtensionAbility component of the form type, which provides APIs related to widgets. - [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md): ExtensionAbility component of the form type, which provides APIs related to widgets.
- [WorkSchedulerExtensionAbility](../reference/apis/js-apis-resourceschedule-workScheduler.md): ExtensionAbility component of the work_scheduler type, which provides callbacks for Work Scheduler tasks. - [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md): ExtensionAbility component of the work_scheduler type, which provides callbacks for Work Scheduler tasks.
- [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which provides an input method framework that can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more. - [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which provides an input method framework that can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more.
...@@ -21,7 +21,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab ...@@ -21,7 +21,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab
- [StaticSubscriberExtensionAbility](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md): ExtensionAbility component of the static_subscriber type, which provides APIs for static broadcast. - [StaticSubscriberExtensionAbility](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md): ExtensionAbility component of the static_subscriber type, which provides APIs for static broadcast.
- [WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md): ExtensionAbility component of the window type, which allows system applications to display UIs of other applications. - [WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md): ExtensionAbility component of the window type, which allows a system application to be embedded in and displayed over another application.
- [EnterpriseAdminExtensionAbility](../reference/apis/js-apis-EnterpriseAdminExtensionAbility.md): ExtensionAbility component of the enterprise_admin type, which provides APIs for processing enterprise management events, such as application installation events on devices and events indicating too many incorrect screen-lock password attempts. - [EnterpriseAdminExtensionAbility](../reference/apis/js-apis-EnterpriseAdminExtensionAbility.md): ExtensionAbility component of the enterprise_admin type, which provides APIs for processing enterprise management events, such as application installation events on devices and events indicating too many incorrect screen-lock password attempts.
......
# Cross-Device Migration # Cross-Device Migration (for System Applications Only)]
## When to Use ## When to Use
Cross-device migration is available only for system applications. The main task is to migrate the current task (including the page control status) of an application to the target device so that the task can continue on it. Cross-device migration supports the following functionalities: The main task of cross-device migration is to migrate the current task (including the page control status) of an application to the target device so that the task can continue on it. Cross-device migration supports the following functionalities:
- Storage and restoration of custom data - Storage and restoration of custom data
......
# Multi-device Collaboration # Multi-device Collaboration (for System Applications Only)
## When to Use ## When to Use
Multi-device coordination is available only for system applications. It involves the following scenarios: Multi-device coordination involves the following scenarios:
- [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned) - [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned)
...@@ -305,7 +305,7 @@ A system application can connect to a service on another device by calling [conn ...@@ -305,7 +305,7 @@ A system application can connect to a service on another device by calling [conn
## Using Cross-Device Ability Call ## Using Cross-Device Ability Call
The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction). The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction (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 {
......
# InputMethodExtensionAbility Development
[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md) is an ExtensionAbility component of the inputMethod type that provides extension capabilities for the input method framework.
InputMethodExtensionAbility can be started or connected by other application components to process transactions in the background based on the request of the caller.
InputMethodExtensionAbility provides related capabilities through the [InputMethodExtensionContext](../reference/apis/js-apis-inputmethod-extension-context.md).
## Implementing an Input Method Application
InputMethodExtensionAbility provides the **onCreate()** and **onDestory()** callbacks, as described below. Override them as required.
- **onCreate**
This callback is triggered when a service is created for the first time. You can perform initialization operations, for example, registering a common event listener.
> **NOTE**
>
> If a service has been created, starting it again does not trigger the **onCreate()** callback.
- **onDestroy**
This callback is triggered when the service is no longer used and the instance is ready for destruction. You can clear resources in this callback, for example, deregister the listener.
## How to Develop
To implement an input method application, manually create an InputMethodExtensionAbility component in DevEco Studio. The procedure is as follows:
In the **ets** directory of the target module, right-click and choose **New** > **Extention Ability** > **InputMethod** to a minimum template of InputMethodExtensionAbility.
> **NOTE**
>
> When compiling the input method application, use the signature at the system_core level. Otherwise, the application will not be able to start the keyboard.
The minimum template implements an input method application with the most basic features, such as starting the keyboard, entering text, and deleting input. You can diversify the feature set of the application by, for example, adding the feature to hide the keyboard.
The minimum template contains four files: **KeyboardController.ts**, **InputMethodService.ts**, **Index.ets**, and **KeyboardKeyData.ts**. The file directory is as follows:
```
/src/main/
├── ets/inputmethodextability
│ └──model/KeyboardController.ts # Shows the keyboard.
│ └──InputMethodService.ts # Customizes a class that inherits from InputMethodExtensionAbility and add the required lifecycle callbacks.
│ └──pages
│ └── Index.ets # Draws the keyboard and adds the input and deletion features.
│ └── KeyboardKeyData.ts # Defines keyboard attributes.
├── resources/base/profile/main_pages.json
```
## File Introduction
1. **InputMethodService.ts** file:
In this file, add the dependency package for importing InputMethodExtensionAbility. Customize a class that inherits from InputMethodExtensionAbility and add the required lifecycle callbacks.
```ts
import InputMethodExtensionAbility from '@ohos.InputMethodExtensionAbility';
import { KeyboardController } from './model/KeyboardController'
export default class InputDemoService extends InputMethodExtensionAbility {
private keyboardController: KeyboardController;
onCreate(want) {
this.keyboardController = new KeyboardController(this.context);
this.keyboardController.onCreate(); // Initialize the window and register an event listener for the input method framework.
}
onDestroy() {
console.log("onDestroy.");
this.context.destroy();
}
}
```
2. **KeyboardController.ts** file:
```ts
import inputMethodEngine from '@ohos.inputMethodEngine';
import display from '@ohos.display';
import windowManager from '@ohos.window';
// Call the getInputMethodAbility API to obtain an instance, and then call the other APIs of the input method framework based on the instance.
globalThis.inputAbility = inputMethodEngine.getInputMethodAbility();
export class KeyboardController {
mContext; // Save the context attribute in InputMethodExtensionAbility.
WINDOW_TYPE_INPUT_METHOD_FLOAT = 2105; // Define the window type. The value 2105 indicates the input method window type, which is used to create an input method application window.
windowName = 'inputApp';
private windowHeight: number = 0;
private windowWidth: number = 0;
private nonBarPosition: number = 0;
private isWindowShowing: boolean = false;
constructor(context) {
this.mContext = context;
}
public onCreate(): void
{
this.initWindow(); // Initialize the window.
this.registerListener(); // Register an event listener for the input method framework.
}
public onDestroy(): void // Destroy the instance.
{
this.unRegisterListener(); // Deregister the event listener.
let win = windowManager.findWindow(this.windowName);
win.destroyWindow(); // Destroy the window.
this.mContext.terminateSelf(); // Terminate the InputMethodExtensionAbility service.
}
private initWindow(): void // Initialize the window.
{
let dis = display.getDefaultDisplaySync();
let dWidth = dis.width;
let dHeight = dis.height;
let keyHeightRate = 0.47;
let keyHeight = dHeight * keyHeightRate;
this.windowWidth = dWidth;
this.windowHeight = keyHeight;
this.nonBarPosition = dHeight - keyHeight;
let config = {
name: this.windowName,
windowType: this.WINDOW_TYPE_INPUT_METHOD_FLOAT,
ctx: this.mContext
}
windowManager.createWindow(config).then((win) => { // Create a window of the specified type.
win.resize(dWidth, keyHeight).then(() => {
win.moveWindowTo(0, this.nonBarPosition).then(() => {
win.setUIContent('pages/InputMethodExtAbility/Index').then(() => {
});
});
});
});
}
private registerListener(): void
{
this.registerInputListener(); // Register an event listener for the input method framework service.
globalThis.inputAbility.on('keyboardShow', () => {// Register an event listener for the keyboard .
if (this.isWindowShowing) {
return;
}
this.isWindowShowing = true;
this.showHighWindow(); // Show the window.
});
...
// Register a listener for keyboard hiding.
}
private registerInputListener() { // Register a listener for the enabling and disabling events of the input method framework service.
globalThis.inputAbility.on('inputStart', (kbController, textInputClient) => {
globalThis.textInputClient = textInputClient; // This is an input method client instance, based on which you can call the functional APIs that the input method framework provides for the input method application.
globalThis.keyboardController = kbController;
})
globalThis.inputAbility.on('inputStop', (imeId) => {
if (imeId == "Bundle name/Ability name") {
this.onDestroy();
}
});
}
private unRegisterListener(): void
{
globalThis.inputAbility.off('inputStart');
globalThis.inputAbility.off('inputStop', () => {});
globalThis.inputAbility.off('keyboardShow');
}
private showHighWindow() {
let win = windowManager.findWindow(this.windowName)
win.resize(this.windowWidth, this.windowHeight).then(() => {
win.moveWindowTo(0, this.nonBarPosition).then(() => {
win.showWindow().then(() => {
this.isWindowShowing = false;
})
})
})
}
}
```
3. **KeyboardKeyData.ts** file:
In this file you can define the content displayed on the soft keyboard.
```ts
export interface sourceListType {
content: string,
}
export let numberSourceListData: sourceListType[] = [
{
content: '1'
},
{
content: '2'
},
{
content: '3'
},
{
content: '4'
},
{
content: '5'
},
{
content: '6'
},
{
content: '7'
},
{
content: '8'
},
{
content: '9'
},
{
content: '0'
}
]
```
4. **Index.ets** file:
This file describes the functions of keys. For example, the number keys print numbers in the text box, and the delete key deletes what's entered.
Add the path to this file to the **src** field in the **resources/base/profile/main_pages.json** file.
```ets
import { numberSourceListData, sourceListType } from './keyboardKeyData'
@Component
struct keyItem {
private keyValue: sourceListType
@State keyBgc: string = "#fff"
@State keyFontColor: string = "#000"
build() {
Column() {
Flex({ direction: FlexDirection.Column,
alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text(this.keyValue.content).fontSize(20).fontColor(this.keyFontColor)
}
}
.backgroundColor(this.keyBgc)
.borderRadius(6)
.width("8%")
.height("65%")
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Down) {
globalThis.textInputClient.insertText(this.keyValue.content);
}
})
}
}
// Component used for deletion.
@Component
export struct deleteItem {
@State keyBgc: string = "#fff"
@State keyFontColor: string = "#000"
build() {
Column() {
Flex({ direction: FlexDirection.Column,
alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text("Delete").fontSize(20).fontColor(this.keyFontColor)
}
}
.backgroundColor(this.keyBgc)
.width("13%")
.borderRadius(6)
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Down) {
globalThis.textInputClient.deleteForward(1);
}
})
}
}
// Numeric keyboard
@Component
struct numberMenu {
private numberList: sourceListType[]
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceEvenly }) {
Flex({ justifyContent: FlexAlign.SpaceBetween }) {
ForEach(this.numberList, (item: sourceListType) => { // First row on the numeric keyboard
keyItem({ keyValue: item })
}, (item: sourceListType) => item.content);
}
.padding({ top: "2%" })
.width("96%")
.height("25%")
Flex({ justifyContent: FlexAlign.SpaceBetween }) {
deleteItem()
}
.width("96%")
.height("25%")
}
}
}
@Entry
@Component
struct Index {
private numberList: sourceListType[] = numberSourceListData
build() {
Stack() {
Flex({
direction: FlexDirection.Column,
alignItems: ItemAlign.Center,
justifyContent: FlexAlign.End
}) {
Flex({
direction: FlexDirection.Column,
alignItems: ItemAlign.Center,
justifyContent: FlexAlign.SpaceBetween
}) {
numberMenu({
numberList: this.numberList
})
}
.align(Alignment.End)
.width("100%")
.height("75%")
}
.height("100%").align(Alignment.End).backgroundColor("#cdd0d7")
}
.position({ x: 0, y: 0 }).zIndex(99999)
}
}
```
Register the InputMethodExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the target module. Set **type** to **"inputMethod"** and **srcEntrance** to the code path of the InputMethodExtensionAbility component.
```ts
{
"module": {
// ...
"extensionAbilities": [
{
"description": "inputMethod",
"icon": "$media:icon",
"name": "InputMethodExtAbility",
"srcEntrance": "./ets/inputmethodextability/InputMethodService.ts",
"type": "inputMethod",
"visible": true,
}
]
}
}
```
...@@ -18,7 +18,7 @@ To develop the Worker mode, perform the following steps: ...@@ -18,7 +18,7 @@ To develop the Worker mode, perform the following steps:
} }
``` ```
2. Create the **worker.js** file based on the configuration in **build-profile.json5**. 2. Create the **worker.ts** file based on the configuration in **build-profile.json5**.
```ts ```ts
import worker from '@ohos.worker'; import worker from '@ohos.worker';
...@@ -58,7 +58,7 @@ To develop the Worker mode, perform the following steps: ...@@ -58,7 +58,7 @@ To develop the Worker mode, perform the following steps:
```ts ```ts
import worker from '@ohos.worker'; import worker from '@ohos.worker';
let wk = new worker.ThreadWorker("../workers/worker.js"); let wk = new worker.ThreadWorker("../workers/worker.ts");
// Send a message to the worker thread. // Send a message to the worker thread.
wk.postMessage("message from main thread.") wk.postMessage("message from main thread.")
...@@ -74,6 +74,6 @@ To develop the Worker mode, perform the following steps: ...@@ -74,6 +74,6 @@ To develop the Worker mode, perform the following steps:
> **NOTE** > **NOTE**
> >
> - If the relative path of **worker.ts** configured in **build-profile.json5** is **./src/main/ets/workers/worker.ts**, pass in the path **entry/ets/workers/worker.ts** when creating a worker thread in the stage model, and pass in the path **../workers/worker.js** when creating a worker thread in the FA model. > - If the relative path of **worker.ts** configured in **build-profile.json5** is **./src/main/ets/workers/worker.ts**, pass in the path **entry/ets/workers/worker.ts** when creating a worker thread in the stage model, and pass in the path **../workers/worker.ts** when creating a worker thread in the FA model.
> >
> - For details about the data types supported between the main thread and worker thread, see [Sequenceable Data Types](../reference/apis/js-apis-worker.md#sequenceable-data-types). > - For details about the data types supported between the main thread and worker thread, see [Sequenceable Data Types](../reference/apis/js-apis-worker.md#sequenceable-data-types).
# Setting the Icon and Name of a Mission Snapshot
Setting a unique icon and name for each mission snapshot of an application helps you better manage the missions and functions of the application.
By default, the **icon** and **label** fields in the [abilities tag](../quick-start/module-configuration-file.md#abilities) of the [module.json5 file](../quick-start/module-configuration-file.md) are used to set the icon and label.
Figure 1 Mission snapshot of a UIAbility
![](figures/mission-list-recent.png)
You can also use [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionicon) and [UIAbilityContext.setMissionLabel()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionlabel) to customize the icon and name for a mission snapshot. For example, for a UIAbility instance with the launch type set to **standard**, you can configure the icon and name for each mission snapshot based on different functions.
This document describes the following operations:
- [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 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).
```ts
let imagePixelMap: PixelMap = undefined; // Obtain the PixelMap information.
this.context.setMissionIcon(imagePixelMap, (err) => {
console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`);
})
```
The display effect is shown below.
Figure 2 Mission snapshot icon
![](figures/mission-set-task-snapshot-icon.png)
## Setting a Mission Snapshot Name
Call [UIAbilityContext.setMissionLabel()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionlabel) to set the name of a mission snapshot.
```ts
this.context.setMissionLabel('test').then(() => {
console.info('setMissionLabel succeeded.');
}).catch((err) => {
console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`);
});
```
The display effect is shown below.
Figure 3 Mission snapshot name
![](figures/mission-set-task-snapshot-label.png)
\ No newline at end of file
...@@ -18,9 +18,9 @@ Each type of ExtensionAbility has its own context. ServiceExtensionAbility has [ ...@@ -18,9 +18,9 @@ Each type of ExtensionAbility has its own context. ServiceExtensionAbility has [
This topic describes how to use ServiceExtensionAbility in the following scenarios: This topic describes how to use ServiceExtensionAbility in the following scenarios:
- [Implementing a Background Service](#implementing-a-background-service) - [Implementing a Background Service (for System Applications Only)](#implementing-a-background-service-for-system-applications-only)
- [Starting a Background Service](#starting-a-background-service) - [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,9 +33,9 @@ This topic describes how to use ServiceExtensionAbility in the following scenari ...@@ -33,9 +33,9 @@ This topic describes how to use ServiceExtensionAbility in the following scenari
> - Third-party applications can connect to ServiceExtensionAbility provided by the system only when they gain focus in the foreground. > - Third-party applications can connect to ServiceExtensionAbility provided by the system only when they gain focus in the foreground.
## Implementing a Background Service ## Implementing a Background Service (for System Applications Only)
This feature applies only to system applications. [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) provides the callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestory()**. Override them as required. The following figure shows the lifecycle of ServiceExtensionAbility. [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) provides the callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestory()**. Override them as required. The following figure shows the lifecycle of ServiceExtensionAbility.
**Figure 1** ServiceExtensionAbility lifecycle **Figure 1** ServiceExtensionAbility lifecycle
![ServiceExtensionAbility-lifecycle](figures/ServiceExtensionAbility-lifecycle.png) ![ServiceExtensionAbility-lifecycle](figures/ServiceExtensionAbility-lifecycle.png)
...@@ -164,9 +164,9 @@ To implement a background service, manually create a ServiceExtensionAbility com ...@@ -164,9 +164,9 @@ To implement a background service, manually create a ServiceExtensionAbility com
``` ```
## Starting a Background Service ## Starting a Background Service (for System Applications Only)
This feature applies only to system applications. A system application uses the [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability) method to start a background service. The [onRequest()](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonrequest) callback is invoked, and the **Want** object passed by the caller is received through the callback. After the background service is started, its lifecycle is independent of that of the client. In other words, even if the client is destroyed, the background service can still run. Therefore, the background service must be stopped by calling [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) when its work is complete. Alternatively, another component can call [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) to stop the background service. A system application uses the [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability) method to start a background service. The [onRequest()](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonrequest) callback is invoked, and the **Want** object passed by the caller is received through the callback. After the background service is started, its lifecycle is independent of that of the client. In other words, even if the client is destroyed, the background service can still run. Therefore, the background service must be stopped by calling [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) when its work is complete. Alternatively, another component can call [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) to stop the background service.
> **NOTE** > **NOTE**
> >
......
# Starting a Remote PageAbility # Starting a Remote PageAbility (for System Applications Only)
This feature applies only to system applications. The **startAbility()** method in the **featureAbility** class is used to start a remote PageAbility. The **startAbility()** method in the **featureAbility** class is used to start a remote PageAbility.
In addition to **'\@ohos.ability.featureAbility'**, you must import **'\@ohos.distributedHardware.deviceManager'**, which provides account-independent distributed device networking capabilities. Then you can use **getTrustedDeviceListSync** of the **DeviceManager** module to obtain the remote device ID and pass the remote device ID in the **want** parameter for starting the remote PageAbility. In addition to **'\@ohos.ability.featureAbility'**, you must import **'\@ohos.distributedHardware.deviceManager'**, which provides account-independent distributed device networking capabilities. Then you can use **getTrustedDeviceListSync** of the **DeviceManager** module to obtain the remote device ID and pass the remote device ID in the **want** parameter for starting the remote PageAbility.
......
# Subscribing to System Environment Variable Changes
System environment variables are system settings (for example, the system language or screen direction) of a device that may change during the running of an application.
By subscribing to the changes of system environment variables, the application can detect the changes in a timely manner and process the changes accordingly, providing better user experience. For example, when the system language changes, the application can display the UI in the new language; when the user rotates the device to landscape or portrait mode, the application can re-arrange the UI to adapt to the new screen orientation and size.
The system environment variable changes are usually triggered by options in **Settings** or icons in **Control Panel**. For details about the system environment variables that support subscription, see [Configuration](../reference/apis/js-apis-app-ability-configuration.md).
In OpenHarmony, you can subscribe to system environment variable changes in the following ways:
- [Using ApplicationContext for Subscription](#using-applicationcontext-for-subscription)
- [Using AbilityStage for Subscription](#using-abilitystage-for-subscription)
- [Using UIAbility for Subscription](#using-uiability-for-subscription)
- [Using ExtensionAbility for Subscription](#using-extensionability-for-subscription)
## Using ApplicationContext for Subscription
[ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md) provides an API for registering a callback function to subscribe to the system environment variable changes. It also provides an API for deregistration so you can release related resources when they are no longer needed.
1. Call **ApplicationContext.on(type: 'environment', callback: EnvironmentCallback)** to subscribe to changes in system environment variables. The code snippet below is used to subscribe to system language changes on a page.
```ts
import common from '@ohos.app.ability.common';
@Entry
@Component
struct Index {
private context = getContext(this) as common.UIAbilityContext;
private callbackId: number; // ID of the subscription for system environment variable changes.
subscribeConfigurationUpdate() {
let systemLanguage: string = this.context.config.language; // Obtain the system language in use.
// 1. Obtain an ApplicationContext object.
let applicationContext = this.context.getApplicationContext();
// 2. Subscribe to system environment variable changes through ApplicationContext.
let environmentCallback = {
onConfigurationUpdated(newConfig) {
console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`);
if (this.systemLanguage !== newConfig.language) {
console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`);
systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison.
}
},
onMemoryLevel(level) {
console.info(`onMemoryLevel level: ${level}`);
}
}
this.callbackId = applicationContext.on('environment', environmentCallback);
}
// Page display.
build() {
// ...
}
}
```
2. Call **ApplicationContext.off(type: 'environment', callbackId: number)** to release the resources.
```ts
import common from '@ohos.app.ability.common';
@Entry
@Component
struct Index {
private context = getContext(this) as common.UIAbilityContext;
private callbackId: number; // ID of the subscription for system environment variable changes.
unsubscribeConfigurationUpdate() {
let applicationContext = this.context.getApplicationContext();
applicationContext.off('environment', this.callbackId);
}
// Page display.
build() {
// ...
}
}
```
## Using AbilityStage for Subscription
The AbilityStage component provides the [AbilityStage.onConfigurationUpdate()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonconfigurationupdate) callback for subscribing to system environment variable changes. This callback is invoked when a system environment variable changes. In this callback, the latest system environment configuration is obtained through the [Configuration](../reference/apis/js-apis-app-ability-configuration.md) object.
> **NOTE**
>
> - AbilityStage is not automatically generated in the default project of DevEco Studio. For details about how to create an AbilityStage file, see [AbilityStage Component Container](abilitystage.md).
> - The callback used to subscribe to system environment variable changes has the same lifecycle as the [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) instance and will be destroyed when the instance is destroyed.
The code snippet below uses the [AbilityStage.onConfigurationUpdate()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonconfigurationupdate) callback to subscribe to the system language changes.
```ts
import AbilityStage from '@ohos.app.ability.AbilityStage';
let systemLanguage: string; // System language in use.
export default class MyAbilityStage extends AbilityStage {
onCreate() {
systemLanguage = this.context.config.language; // Obtain the system language in use when the AbilityStage instance is loaded for the first time.
console.info(`systemLanguage is ${systemLanguage} `);
}
onConfigurationUpdate(newConfig) {
console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`);
if (systemLanguage !== newConfig.language) {
console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`);
systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison.
}
}
}
```
## Using UIAbility for Subscription
The UIAbility component provides the **UIAbility.onConfigurationUpdate()** callback for subscribing to system environment variable changes. This callback is invoked when a system environment variable changes. In this callback, the latest system environment configuration is obtained through the [Configuration](../reference/apis/js-apis-app-ability-configuration.md) object, without restarting the UIAbility.
> **NOTE**
>
> The callback used to subscribe to system environment variable changes has the same lifecycle as the UIAbility instance and will be destroyed when the instance is destroyed.
The code snippet below uses the **onConfigurationUpdate()** callback to subscribe to the system language changes.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
let systemLanguage: string; // System language in use.
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
systemLanguage = this.context.config.language; // Obtain the system language in use when the UIAbility instance is loaded for the first time.
console.info(`systemLanguage is ${systemLanguage} `);
}
onConfigurationUpdate(newConfig) {
console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`);
if (systemLanguage !== newConfig.language) {
console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`);
systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison.
}
}
// ...
}
```
## Using ExtensionAbility for Subscription
The ExtensionAbility component provides the **onConfigurationUpdate()** callback for subscribing system environment variable changes. This callback is invoked when a system environment variable changes. In this callback, the latest system environment configuration is obtained through the [Configuration](../reference/apis/js-apis-app-ability-configuration.md) object.
> **NOTE**
>
> The callback used to subscribe to system environment variable changes has the same lifecycle as the ExtensionAbility instance and will be destroyed when the instance is destroyed.
The code snippet below uses FormExtensionAbility as an example to describe how to use the **onConfigurationUpdate()** callback to subscribe to system environment variable changes.
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class EntryFormAbility extends FormExtensionAbility {
onConfigurationUpdate(newConfig) {
console.info(`newConfig is ${JSON.stringify(newConfig)}`);
}
// ...
}
```
...@@ -15,9 +15,11 @@ This topic describes the UIAbility interaction modes in the following scenarios. ...@@ -15,9 +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 (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](#using-ability-call-to-implement-uiability-interaction) - [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
...@@ -202,8 +204,7 @@ This section describes how to start the UIAbility of another application through ...@@ -202,8 +204,7 @@ This section describes how to start the UIAbility of another application through
``` ```
The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select. The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select.
![](figures/uiability-intra-device-interaction.png)
![uiability-intra-device-interaction](figures/uiability-intra-device-interaction.png)
3. To stop the **UIAbility** instance after the document application is used, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself). 3. To stop the **UIAbility** instance after the document application is used, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself).
...@@ -307,6 +308,55 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -307,6 +308,55 @@ If you want to obtain the return result when using implicit Want to start the UI
}) })
``` ```
## 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.
In full-screen mode, an application occupies the entire screen after being started. Users cannot view other windows or applications. This mode is suitable for an application that requires users to focus on a specific task or UI.
In floating window mode, an application is displayed on the screen as a floating window after being started. Users can easily switch to other windows or applications. The mode is suitable for an application that requires users to process multiple tasks at the same time.
In split-screen mode, two applications occupy the entire screen, with one on the left or in the upper part of the screen and the other on the right or in the lower part. This mode helps users improve multi-task processing efficiency.
The window mode is specified by the **windowMode** field in the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter of [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability).
> **NOTE**
>
> 1. If the **windowMode** field is not specified, the UIAbility is started in the default window mode.
> 2. To ensure that the application can be displayed in the required window mode, check the **supportWindowMode** field in the [abilities tag](../quick-start/module-configuration-file.md#abilities) in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility and make sure the specified window mode is supported.
The following uses the floating window mode as an example to describe how to start the FuncAbility from the EntryAbility page.
1. Add the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability).
2. Set the **windowMode** field in the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter to **WINDOW_MODE_FLOATING**, indicating that the UIAbility will be displayed in a floating window.
For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
let wantInfo = {
deviceId: '', // An empty deviceId indicates the local device.
bundleName: 'com.example.myapplication',
abilityName: 'FuncAbility',
moduleName: 'module1', // moduleName is optional.
parameters: {// Custom information.
info: 'From the Index page of EntryAbility',
},
}
let options = {
windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FLOATING
}
// context is the ability-level context of the initiator UIAbility.
this.context.startAbility(wantInfo, options).then(() => {
// ...
}).catch((err) => {
// ...
})
```
The display effect is shown below.
![](figures/start-uiability-floating-window.png)
## Starting a Specified Page of UIAbility ## Starting a Specified Page of UIAbility
...@@ -422,9 +472,9 @@ In summary, when a UIAbility instance of application A has been created and the ...@@ -422,9 +472,9 @@ In summary, when a UIAbility instance of application A has been created and the
> When the [launch type of the callee UIAbility](uiability-launch-type.md) is set to **standard**, a new instance is created each time the callee UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked. > When the [launch type of the callee UIAbility](uiability-launch-type.md) is set to **standard**, a new instance is created each time the callee UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked.
## Using Ability Call to Implement UIAbility Interaction ## Using Ability Call to Implement UIAbility Interaction (for System Applications Only)
This feature applies only to system applications. Ability call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two UIAbility instances (caller ability and callee ability) through IPC. Ability call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two UIAbility instances (caller ability and callee ability) through IPC.
The core API used for the ability call is **startAbilityByCall**, which differs from **startAbility** in the following ways: The core API used for the ability call is **startAbilityByCall**, which differs from **startAbility** in the following ways:
...@@ -449,9 +499,9 @@ Ability call is usually used in the following scenarios: ...@@ -449,9 +499,9 @@ Ability call is usually used in the following scenarios:
The following figure shows the ability call process. The following figure shows the ability call process.
Figure 1 Ability call process Figure 1 Ability call process
![call](figures/call.png) ![call](figures/call.png)
- The caller ability uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the callee ability. - The caller ability uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the callee ability.
...@@ -476,8 +526,8 @@ The following table describes the main APIs used for the ability call. For detai ...@@ -476,8 +526,8 @@ The following table describes the main APIs used for the ability call. For detai
| 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.|
...@@ -495,37 +545,39 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -495,37 +545,39 @@ For the callee ability, implement the callback to receive data and the methods t
1. Configure the ability launch type. 1. Configure the ability launch type.
Set **launchType** of the callee ability to **singleton** in the **module.json5** file. Set **launchType** of the callee ability to **singleton** in the **module.json5** file.
| JSON Field| Description| | JSON Field| Description|
| -------- | -------- | | -------- | -------- |
| "launchType" | Ability launch type. Set this parameter to **singleton**.| | "launchType" | Ability launch type. Set this parameter to **singleton**.|
An example of the ability configuration is as follows: An example of the ability configuration is as follows:
```json
"abilities":[{ ```json
"name": ".CalleeAbility", "abilities":[{
"srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts", "name": ".CalleeAbility",
"launchType": "singleton", "srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts",
"description": "$string:CalleeAbility_desc", "launchType": "singleton",
"icon": "$media:icon", "description": "$string:CalleeAbility_desc",
"label": "$string:CalleeAbility_label", "icon": "$media:icon",
"visible": true "label": "$string:CalleeAbility_label",
}] "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 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 = ""
...@@ -534,15 +586,15 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -534,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
} }
} }
...@@ -550,8 +602,7 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -550,8 +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';
...@@ -559,14 +610,14 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -559,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 {
...@@ -588,7 +639,6 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -588,7 +639,6 @@ For the callee ability, implement the callback to receive data and the methods t
} }
``` ```
### Accessing the Callee Ability ### Accessing the Callee Ability
1. Import the **UIAbility** module. 1. Import the **UIAbility** module.
...@@ -598,9 +648,9 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -598,9 +648,9 @@ For the callee ability, implement the callback to receive data and the methods t
``` ```
2. Obtain the caller interface. 2. Obtain the caller interface.
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
// Register the onRelease() listener of the caller ability. // Register the onRelease() listener of the caller ability.
private regOnRelease(caller) { private regOnRelease(caller) {
......
...@@ -17,13 +17,10 @@ The launch type of the UIAbility component refers to the state of the UIAbility ...@@ -17,13 +17,10 @@ The launch type of the UIAbility component refers to the state of the UIAbility
Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, if a UIAbility instance of this type already exists in the application process, the instance is reused. Therefore, only one UIAbility instance of this type exists in the system, that is, displayed in **Recents**. Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, if a UIAbility instance of this type already exists in the application process, the instance is reused. Therefore, only one UIAbility instance of this type exists in the system, that is, displayed in **Recents**.
**Figure 1** Demonstration effect in singleton mode **Figure 1** Demonstration effect in singleton mode
![uiability-launch-type1](figures/uiability-launch-type1.png)
![uiability-launch-type1](figures/uiability-launch-type1.png) > **NOTE**<br>Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **singleton**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not.
> **NOTE**
>
> Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **singleton**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not.
To use the singleton mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **singleton**. To use the singleton mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **singleton**.
...@@ -47,9 +44,8 @@ To use the singleton mode, set **launchType** in the [module.json5 configuration ...@@ -47,9 +44,8 @@ To use the singleton mode, set **launchType** in the [module.json5 configuration
In standard mode, each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a new UIAbility instance of this type is created in the application process. Multiple UIAbility instances of this type are displayed in **Recents**. In standard mode, each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a new UIAbility instance of this type is created in the application process. Multiple UIAbility instances of this type are displayed in **Recents**.
**Figure 2** Demonstration effect in standard mode **Figure 2** Demonstration effect in standard mode
![standard-mode](figures/standard-mode.png)
![standard-mode](figures/standard-mode.png)
To use the standard mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **standard**. To use the standard mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **standard**.
...@@ -73,14 +69,13 @@ To use the standard mode, set **launchType** in the [module.json5 configuration ...@@ -73,14 +69,13 @@ To use the standard mode, set **launchType** in the [module.json5 configuration
The **specified** mode is used in some special scenarios. For example, in a document application, you want a document instance to be created each time you create a document, but you want to use the same document instance when you repeatedly open an existing document. The **specified** mode is used in some special scenarios. For example, in a document application, you want a document instance to be created each time you create a document, but you want to use the same document instance when you repeatedly open an existing document.
**Figure 3** Demonstration effect in specified mode **Figure 3** Demonstration effect in specified mode
![uiability-launch-type2](figures/uiability-launch-type2.png)
![uiability-launch-type2](figures/uiability-launch-type2.png) For example, there are two UIAbility components: EntryAbility and SpecifiedAbility (with the launch type **specified**). You are required to start SpecifiedAbility from EntryAbility.
For example, there are EntryAbility and SpecifiedAbility, and the launch type of SpecifiedAbility is set to **specified**. You are required to start SpecifiedAbility from EntryAbility. 1. In SpecifiedAbility, set the **launchType** field in the [module.json5 file](../quick-start/module-configuration-file.md) to **specified**.
1. In SpecifiedAbility, set the **launchType** field in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **specified**.
```json ```json
{ {
"module": { "module": {
...@@ -95,9 +90,8 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of ...@@ -95,9 +90,8 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of
} }
``` ```
2. Before a UIAbility instance is created, you can create a unique string key for the instance. The key is bound to the UIAbility instance when it is created. Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the application is asked which UIAbility instance is used to respond to the [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) request. 2. Create a unique string key for the instance. Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the application, based on the key, identifies the UIAbility instance used to respond to the request. In EntryAbility, add a custom parameter, for example, **instanceKey**, to the **want** parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to distinguish the UIAbility instance.
In EntryAbility, add a custom parameter, for example, **instanceKey**, to the [want](want-overview.md) parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to distinguish the UIAbility instances.
```ts ```ts
// Configure an independent key for each UIAbility instance. // Configure an independent key for each UIAbility instance.
// For example, in the document usage scenario, use the document path as the key. // For example, in the document usage scenario, use the document path as the key.
...@@ -121,10 +115,11 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of ...@@ -121,10 +115,11 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of
// ... // ...
}) })
``` ```
3. During running, the internal service of UIAbility determines whether to create multiple instances. If the key is matched, the UIAbility instance bound to the key is started. Otherwise, a new UIAbility instance is created. 3. Before SpecifiedAbility is started, the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of the corresponding AbilityStage instance is invoked to obtain the key of the UIAbility, because the launch type of SpecifiedAbility is set to **specified**. If a UIAbility instance matching the key exists, the system starts the UIAbility instance and invokes its [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback. Otherwise, the system creates a new UIAbility instance and invokes its [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks.
The launch type of SpecifiedAbility is set to **specified**. Before SpecifiedAbility is started, the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of the corresponding AbilityStage instance is invoked to parse the input **want** parameter and obtain the custom parameter **instanceKey**. A string key identifier is returned through the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of the AbilityStage instance. [If the returned key corresponds to a started UIAbility instance](mission-management-launch-type.md#fig14520125175314), that UIAbility instance is switched to the foreground and gains focus again. Otherwise, a new instance is created and started.
In the sample code, the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback parses the **want** parameter to obtain the custom parameter **instanceKey**. The service logic returns a key string based on **instanceKey** parameter to identify the UIAbility instance. If the returned key maps to a started UIAbility instance, the system pulls the UIAbility instance back to the foreground and obtains the focus. If the returned key does not map to a started UIAbility instance, the system creates a new UIAbility instance and starts it.
```ts ```ts
import AbilityStage from '@ohos.app.ability.AbilityStage'; import AbilityStage from '@ohos.app.ability.AbilityStage';
...@@ -133,7 +128,7 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of ...@@ -133,7 +128,7 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of
// In the AbilityStage instance of the callee, a key value corresponding to a UIAbility instance is returned for UIAbility whose launch type is specified. // In the AbilityStage instance of the callee, a key value corresponding to a UIAbility instance is returned for UIAbility whose launch type is specified.
// In this example, SpecifiedAbility of module1 is returned. // In this example, SpecifiedAbility of module1 is returned.
if (want.abilityName === 'SpecifiedAbility') { if (want.abilityName === 'SpecifiedAbility') {
// The returned string key is a custom string. // The returned key string is a custom string.
return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`; return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`;
} }
...@@ -141,22 +136,17 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of ...@@ -141,22 +136,17 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of
} }
} }
``` ```
> **NOTE** > **NOTE**<br>
> >
> 1. Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **specified**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, and the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) matches a created UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not. > 1. Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **specified**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, and the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) matches a created UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not.
> 2. AbilityStage is not automatically generated in the default project of DevEco Studio. For details about how to create an AbilityStage file, see [AbilityStage Component Container](abilitystage.md). > 2. AbilityStage is not automatically generated in the default project of DevEco Studio. For details about how to create an AbilityStage file, see [AbilityStage Component Container](abilitystage.md).
For example, in the document application, different key values are bound to different document instances. Each time a document is created, a new key value (for example, file path) is passed, and a new UIAbility instance is created when UIAbility is started in AbilityStage. However, when you open an existing document, the same UIAbility instance is started again in AbilityStage.
The following steps are used as an example. For example, in the document application, different keys are bound to different document instances. Each time a document is created, a new key (for example, file path) is passed, and a new UIAbility instance is created when UIAbility is started in AbilityStage. However, when you open an existing document, the same UIAbility instance is started again in AbilityStage.
The following steps are used as an example.
1. Open file A. A UIAbility instance, for example, UIAbility instance 1, is started. 1. Open file A. A UIAbility instance, for example, UIAbility instance 1, is started.
2. Close the process of file A in **Recents**. UIAbility instance 1 is destroyed. Return to the home screen and open file A again. A new UIAbility instance is started, for example, UIAbility instance 2. 2. Close the process of file A in **Recents**. UIAbility instance 1 is destroyed. Return to the home screen and open file A again. A new UIAbility instance is started, for example, UIAbility instance 2.
3. Return to the home screen and open file B. A new UIAbility instance is started, for example, UIAbility instance 3. 3. Return to the home screen and open file B. A new UIAbility instance is started, for example, UIAbility instance 3.
4. Return to the home screen and open file A again. UIAbility instance 2 is started. This is because the system automatically matches the key of the UIAbility instance and starts the UIAbility instance that has a matching key. In this example, UIAbility instance 2 has the same key as file A. Therefore, the system pulls back UIAbility instance 2 and focuses it without creating a new instance.
4. Return to the home screen and open file A again. UIAbility instance 2 is started.
<!--no_check-->
\ No newline at end of file
...@@ -3,9 +3,11 @@ ...@@ -3,9 +3,11 @@
## Overview ## Overview
UIAbility has the UI and is mainly used for user interaction. UIAbility is a type of application component that provides the UI for user interaction.
UIAbility is the basic unit scheduled by the system and provides a window for applications to draw UIs. A UIAbility component can implement a functional module through multiple pages. Each UIAbility component instance corresponds to a mission in **Recents**. UIAbility is the basic unit scheduled by the system and provides a window for applications to draw UIs. An application can contain one or more UIAbility components. For example, for a payment application, you can use two UIAbility components to carry the entry and payment functionalities. You are advised to use one UIAbility component to carry the same functional module, with multiple pages (if necessary).
Each UIAbility component instance is displayed as a mission in Recents.
## Privacy Statement Configuration ## Privacy Statement Configuration
...@@ -32,8 +34,3 @@ To enable an application to properly use a UIAbility component, declare the UIAb ...@@ -32,8 +34,3 @@ To enable an application to properly use a UIAbility component, declare the UIAb
} }
} }
``` ```
> **NOTE**
>
> For the ability composition, see [Adding an Ability to a Module](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-ability-0000001218280664-V3).
# WindowExtensionAbility
[WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md) is a type of ExtensionAbility component that allows a system application to be embedded in and displayed over another application.
The WindowExtensionAbility component must be used together with the [AbilityComponent](../reference/arkui-ts/ts-container-ability-component.md) to process services of the started application. WindowExtensionAbility is run in connection mode. A system application must use the AbilityComponent to start the WindowExtensionAbility component.
Each ExtensionAbility has its own context. For WindowExtensionAbility,
the context is [WindowExtensionContext](../reference/apis/js-apis-inner-application-windowExtensionContext.md).
> **NOTE**
>
> **WindowExtensionAbility** is a system API. To embed a third-party application in another application and display it over the application, switch to the full SDK by following the instructions provided in [Guide to Switching to Full SDK](../../application-dev/quick-start/full-sdk-switch-guide.md).
>
## Setting an Embedded Ability (for System Applications Only)
The **WindowExtensionAbility** class provides **onConnect()**, **onDisconnect()**, and **onWindowReady()** lifecycle callbacks, which can be overridden.
- The **onWindowReady()** callback is invoked when a window is created for the ability.
- The **onConnect()** callback is invoked when the AbilityComponent corresponding to the window connects to the ability.
- The **onDisconnect()** callback is invoked when the AbilityComponent disconnects from the ability.
**How to Develop**
To implement an embedded application, manually create a WindowExtensionAbility in DevEco Studio as follows:
1. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **WindowExtAbility**.
2. Right-click the **WindowExtAbility** directory, and choose **New > TypeScript File** to create a file named **WindowExtAbility.ts**.
3. Open the **WindowExtAbility.ts** file and import the dependency package of **WindowExtensionAbility**. Customize a class that inherits from **WindowExtensionAbility** and implement the **onWindowReady()**, **onConnect()**, and **onDisconnect()** lifecycle callbacks.
```ts
import Extension from '@ohos.application.WindowExtensionAbility'
export default class WindowExtAbility extends Extension {
onWindowReady(window) {
window.loadContent('WindowExtAbility/pages/index1').then(() => {
window.getProperties().then((pro) => {
console.log("WindowExtension " + JSON.stringify(pro));
})
window.show();
})
}
onConnect(want) {
console.info('JSWindowExtension onConnect ' + want.abilityName);
}
onDisconnect(want) {
console.info('JSWindowExtension onDisconnect ' + want.abilityName);
}
}
```
4. Register the WindowExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the **Module** project. Set **type** to **"window"** and **srcEntrance** to the code path of the ExtensionAbility component.
```json
{
"module": {
"extensionAbilities": [
{
"name": "WindowExtAbility",
"srcEntrance": "./ets/WindowExtAbility/WindowExtAbility.ts",
"icon": "$media:icon",
"description": "WindowExtension",
"type": "window",
"visible": true,
}
],
}
}
```
## Starting an Embedded Ability (for System Applications Only)
System applications can load the created WindowExtensionAbility through the AbilityComponent.
**How to Develop**
1. To connect to an embedded application, add the AbilityComponent to the corresponding pages in the DevEco Studio project.
2. Set **bundleName** and **abilityName** in the AbilityComponent.
3. Set the width and height. The sample code is as follows:
```ts
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
AbilityComponent({ abilityName: "WindowExtAbility", bundleName: "com.example.WindowExtAbility"})
.width(500)
.height(500)
}
.width('100%')
}
.height('100%')
.backgroundColor(0x64BB5c)
}
}
```
...@@ -108,7 +108,7 @@ You write a UI test script based on the unit test framework, adding the invoking ...@@ -108,7 +108,7 @@ You write a UI test script based on the unit test framework, adding the invoking
In this example, the UI test script is written based on the preceding unit test script. First, add the dependency package, as shown below: In this example, the UI test script is written based on the preceding unit test script. First, add the dependency package, as shown below:
```js ```js
import {UiDriver,BY,UiComponent,MatchPattern} from '@ohos.uitest' import {Driver,ON,Component,MatchPattern} from '@ohos.uitest'
``` ```
Then, write specific test code. Specifically, implement the click action on the started application page and add checkpoint check cases. Then, write specific test code. Specifically, implement the click action on the started application page and add checkpoint check cases.
...@@ -131,16 +131,16 @@ export default function abilityTest() { ...@@ -131,16 +131,16 @@ export default function abilityTest() {
expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility'); expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility');
}) })
//ui test code //ui test code
//init uidriver //init driver
var driver = await UiDriver.create(); var driver = await Driver.create();
await driver.delayMs(1000); await driver.delayMs(1000);
//find button by text 'Next' //find button on text 'Next'
var button = await driver.findComponent(BY.text('Next')); var button = await driver.findComponent(ON.text('Next'));
//click button //click button
await button.click(); await button.click();
await driver.delayMs(1000); await driver.delayMs(1000);
//check text //check text
await driver.assertComponentExist(BY.text('after click')); await driver.assertComponentExist(ON.text('after click'));
await driver.pressBack(); await driver.pressBack();
done(); done();
}) })
...@@ -195,14 +195,15 @@ The framework supports multiple test case execution modes, which are triggered b ...@@ -195,14 +195,15 @@ The framework supports multiple test case execution modes, which are triggered b
| itName | Test case to be executed. | {itName} | -s itName testAttributeIt | | itName | Test case to be executed. | {itName} | -s itName testAttributeIt |
| timeout | Timeout interval for executing a test case. | Positive integer (unit: ms). If no value is set, the default value 5000 is used. | -s timeout 15000 | | timeout | Timeout interval for executing a test case. | Positive integer (unit: ms). If no value is set, the default value 5000 is used. | -s timeout 15000 |
| breakOnError | Whether to enable break-on-error mode. When this mode is enabled, the test execution process exits if a test assertion error or any other error occurs.| **true**/**false** (default value) | -s breakOnError true | | breakOnError | Whether to enable break-on-error mode. When this mode is enabled, the test execution process exits if a test assertion error or any other error occurs.| **true**/**false** (default value) | -s breakOnError true |
| random | Whether to execute test cases in random sequence.| **true**/**false** (default value) | -s random true |
| testType | Type of the test case to be executed. | function, performance, power, reliability, security, global, compatibility, user, standard, safety, resilience| -s testType function | | testType | Type of the test case to be executed. | function, performance, power, reliability, security, global, compatibility, user, standard, safety, resilience| -s testType function |
| level | Level of the test case to be executed. | 0, 1, 2, 3, 4 | -s level 0 | | level | Level of the test case to be executed. | 0, 1, 2, 3, 4 | -s level 0 |
| size | Size of the test case to be executed. | small, medium, large | -s size small | | size | Size of the test case to be executed. | small, medium, large | -s size small |
| stress | Number of times that the test case is executed. | Positive integer | -s stress 1000 | | stress | Number of times that the test case is executed. | Positive integer | -s stress 1000 |
**Running Commands** **Running Commands**
> Configure hdc-related environment variables, and then perform the following: > Before running commands in the CLI, make sure hdc-related environment variables have been configured.
- Open the CLI. - Open the CLI.
- Run the **aa test** commands. - Run the **aa test** commands.
......
...@@ -5,6 +5,10 @@ ...@@ -5,6 +5,10 @@
- [HTTP Data Request](http-request.md) - [HTTP Data Request](http-request.md)
- [WebSocket Connection](websocket-connection.md) - [WebSocket Connection](websocket-connection.md)
- [Socket Connection](socket-connection.md) - [Socket Connection](socket-connection.md)
- [Network Policy Management](net-policy-management.md)
- [Network Sharing](net-sharing.md)
- [Ethernet Connection](net-ethernet.md)
- [Network Connection Management](net-connection-manager.md)
- IPC & RPC - IPC & RPC
- [IPC & RPC Overview](ipc-rpc-overview.md) - [IPC & RPC Overview](ipc-rpc-overview.md)
- [IPC & RPC Development](ipc-rpc-development-guideline.md) - [IPC & RPC Development](ipc-rpc-development-guideline.md)
......
# Network Connection Management
## Introduction
The Network Connection Management module provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution.
> **NOTE**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-connection.md).
## Basic Concepts
- Producer: a provider of data networks, such as Wi-Fi, cellular, and Ethernet.
- Consumer: a user of data networks, for example, an application or a system service.
- Network probe: a mechanism used to detect the network availability to prevent the switch from an available network to an unavailable network. The probe type can be binding network detection, DNS detection, HTTP detection, or HTTPS detection.
- Network selection: a mechanism used to select the optimal network when multiple networks coexist. It is triggered when the network status, network information, or network quality evaluation score changes.
## **Constraints**
- Programming language: C++ and JS
- System: Linux kernel
- The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## When to Use
Typical application scenarios of network connection management are as follows:
- Subscribing to status changes of the specified network
- Obtaining the list of all registered networks
- Querying network connection information based on the data network
- Resolving the domain name of a network to obtain all IP addresses
The following describes the development procedure specific to each application scenario.
## Available APIs
For the complete list of APIs and example code, see [Network Connection Management](../reference/apis/js-apis-net-connection.md).
| Type| API| Description|
| ---- | ---- | ---- |
| ohos.net.connection | function getDefaultNet(callback: AsyncCallback\<NetHandle>): void; |Creates a **NetHandle** object that contains the **netId** of the default network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getGlobalHttpProxy<sup>10+</sup>(callback: AsyncCallback\<HttpProxy>): void;| Obtains the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function setGlobalHttpProxy<sup>10+</sup>(httpProxy: HttpProxy, callback: AsyncCallback<void>): void;| Sets the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getAppNet<sup>9+</sup>(callback: AsyncCallback\<NetHandle>): void;| Obtains a **NetHandle** object that contains the **netId** of the network bound to the application. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function setAppNet<sup>9+</sup>(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Binds an application to the specified network. The application can access the external network only through this network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getDefaultNetSync<sup>9+</sup>(): NetHandle; |Obtains the default active data network in synchronous mode. You can use **getNetCapabilities** to obtain information such as the network type and capabilities.|
| ohos.net.connection | function hasDefaultNet(callback: AsyncCallback\<boolean>): void; |Checks whether the default network is available. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getAllNets(callback: AsyncCallback\<Array\<NetHandle>>): void;| Obtains the list of **NetHandle** objects of the connected network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void; |Obtains link information of the default network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void; |Obtains the capability set of the default network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function isDefaultNetMetered<sup>9+</sup>(callback: AsyncCallback<boolean>): void; |Checks whether the data traffic usage on the current network is metered. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function reportNetConnected(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void; |Obtains all IP addresses of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function enableAirplaneMode(callback: AsyncCallback\<void>): void; | Enables the airplane mode. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function disableAirplaneMode(callback: AsyncCallback\<void>): void;| Disables the airplane mode. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection; | Creates a **NetConnection** object. **netSpecifier** specifies the network, and **timeout** specifies the timeout interval in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used.|
| ohos.net.connection.NetHandle | bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): void; | Binds a **TCPSocket** or **UDPSocket** to the current network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection.NetHandle | getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void; |Obtains all IP addresses of the default network by resolving the domain name. This API uses an asynchronous callback to return the result.|
| ohos.net.connection.NetHandle | getAddressByName(host: string, callback: AsyncCallback\<NetAddress>): void; |Obtains an IP address of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.|
| ohos.net.connection.NetConnection | on(type: 'netAvailable', callback: Callback\<NetHandle>): void; |Subscribes to **netAvailable** events.|
| ohos.net.connection.NetConnection | on(type: 'netCapabilitiesChange', callback: Callback\<{ netHandle: NetHandle, netCap: NetCapabilities }>): void; |Subscribes to **netCapabilitiesChange** events.|
| ohos.net.connection.NetConnection | on(type: 'netConnectionPropertiesChange', callback: Callback\<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void; |Subscribes to **netConnectionPropertiesChange** events.|
| ohos.net.connection.NetConnection | on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void; |Subscribes to **netBlockStatusChange** events.|
| ohos.net.connection.NetConnection | on(type: 'netLost', callback: Callback\<NetHandle>): void; |Subscribes to **netLost** events.|
| ohos.net.connection.NetConnection | on(type: 'netUnavailable', callback: Callback\<void>): void; |Subscribes to **netUnavailable** events.|
| ohos.net.connection.NetConnection | register(callback: AsyncCallback\<void>): void; |Registers an observer for the default network or the network specified in **createNetConnection**.|
| ohos.net.connection.NetConnection | unregister(callback: AsyncCallback\<void>): void; |Unregisters the observer for the default network or the network specified in **createNetConnection**.|
## Subscribing to Status Changes of the Specified Network
1. Import the connection namespace from **@ohos.net.connection.d.ts**.
2. Call **createNetConnection()** to create a **NetConnection** object. You can specify the network type, capability, and timeout interval. If you do not specify parameters, the default values will be used.
3. Call **conn.on()** to subscribe to the target event. You must pass in **type** and **callback**.
4. Call **conn.register()** to subscribe to network status changes of the specified network.
5. When the network is available, the callback will be invoked to return the **netAvailable** event. When the network is unavailable, the callback will be invoked to return the **netUnavailable** event.
6. Call **conn.unregister()** to unsubscribe from the network status changes if required.
```js
// Import the connection namespace.
import connection from '@ohos.net.connection'
let netCap = {
// Assume that the default network is Wi-Fi. If you need to create a cellular network connection, set the network type to CELLULAR.
bearerTypes: [connection.NetBearType.BEARER_CELLULAR],
// Set the network capability to INTERNET.
networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET],
};
let netSpec = {
netCapabilities: netCap,
};
// Set the timeout value to 10s. The default value is 0.
let timeout = 10 * 1000;
// Create a NetConnection object.
let conn = connection.createNetConnection(netSpec, timeout);
// Listen to network status change events. If the network is available, an on_netAvailable event is returned.
conn.on('netAvailable', (data=> {
console.log("net is available, netId is " + data.netId);
}));
// Listen to network status change events. If the network is unavailable, an on_netUnavailable event is returned.
conn.on('netUnavailable', (data=> {
console.log("net is unavailable, netId is " + data.netId);
}));
// Register an observer for network status changes.
conn.register((err, data) => {});
// Unregister the observer for network status changes.
conn.unregister((err, data) => {});
```
## Obtaining the List of All Registered Networks
### How to Develop
1. Import the connection namespace from **@ohos.net.connection.d.ts**.
2. Call **getAllNets** to obtain the list of all connected networks.
```js
// Import the connection namespace.
import connection from '@ohos.net.connection'
// Obtain the list of all connected networks.
connection.getAllNets((err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
if (data) {
this.netList = data;
}
})
```
## Querying Network Capability Information and Connection Information of Specified Data Network
### How to Develop
1. Import the connection namespace from **@ohos.net.connection.d.ts**.
2. Call **getDefaultNet** to obtain the default data network via **NetHandle** or call **getAllNets** to obtain the list of all connected networks via **Array\<NetHandle>**.
3. Call **getNetCapabilities** to obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type (cellular, Wi-Fi, or Ethernet network) and the specific network capabilities.
4. Call **getConnectionProperties** to obtain the connection information of the data network specified by **NetHandle**.
```js
// Import the connection namespace.
import connection from '@ohos.net.connection'
// Call getDefaultNet to obtain the default data network specified by **NetHandle**.
connection.getDefaultNet((err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
if (data) {
this.netHandle = data;
}
})
// Obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type and specific network capabilities.
connection.getNetCapabilities(this.netHandle, (err, data) => {
console.log(JSON.stringify(err));
// Obtain the network type via bearerTypes.
for (let item of data.bearerTypes) {
if (item == 0) {
// Cellular network
console.log(JSON.stringify("BEARER_CELLULAR"));
} else if (item == 1) {
// Wi-Fi network
console.log(JSON.stringify("BEARER_WIFI"));
} else if (item == 3) {
// Ethernet network
console.log(JSON.stringify("BEARER_ETHERNET"));
}
}
// Obtain the specific network capabilities via networkCap.
for (let item of data.networkCap) {
if (item == 0) {
// The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.
console.log(JSON.stringify("NET_CAPABILITY_MMS"));
} else if (item == 11) {
// The network traffic is not metered.
console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED"));
} else if (item == 12) {
// The network has the Internet access capability, which is set by the network provider.
console.log(JSON.stringify("NET_CAPABILITY_INTERNET"));
} else if (item == 15) {
// The network does not use a Virtual Private Network (VPN).
console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN"));
} else if (item == 16) {
// The Internet access capability of the network is successfully verified by the connection management module.
console.log(JSON.stringify("NET_CAPABILITY_VALIDATED"));
}
}
})
// Obtain the connection information of the data network specified by NetHandle. Connection information includes link and route information.
connection.getConnectionProperties(this.netHandle, (err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
})
// Call getAllNets to obtain the list of all connected networks via Array<NetHandle>.
connection.getAllNets((err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
if (data) {
this.netList = data;
}
})
for (let item of this.netList) {
// Obtain the network capability information of the network specified by each netHandle on the network list cyclically.
connection.getNetCapabilities(item, (err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
})
// Obtain the connection information of the network specified by each netHandle on the network list cyclically.
connection.getConnectionProperties(item, (err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
})
}
```
## Resolving the domain name of a network to obtain all IP addresses
### How to Develop
1. Import the connection namespace from **@ohos.net.connection.d.ts**.
2. Call **getAddressesByName** to use the default network to resolve the host name to obtain the list of all IP addresses.
```js
// Import the connection namespace.
import connection from '@ohos.net.connection'
// Use the default network to resolve the host name to obtain the list of all IP addresses.
connection.getAddressesByName(this.host, (err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
})
```
# Ethernet Connection
## Introduction
The Ethernet Connection module allows a device to access the Internet through a network cable.
After a device is connected to the Ethernet through a network cable, the device can obtain a series of network attributes, such as the dynamically allocated IP address, subnet mask, gateway, and DNS. You can manually configure and obtain the network attributes of the device in static mode.
> **NOTE**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-ethernet.md).
## **Constraints**
- Programming language: C++ and JS
- System: Linux kernel
- 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.
## When to Use
Typical application scenarios of Ethernet connection are as follows:
- Dynamically assigning a series of network attributes, such as the IP address, subnet mask, gateway, and DNS in DHCP mode to enable network access
- Configuring a series of network attributes, such as the IP address, subnet mask, gateway, and DNS, in static mode to enable network access.
The following describes the development procedure specific to each application scenario.
## Available APIs
For the complete list of APIs and example code, see [Ethernet Connection](../reference/apis/js-apis-net-ethernet.md).
| Type| API| Description|
| ---- | ---- | ---- |
| ohos.net.ethernet | function setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallback\<void>): void | Configures the network attributes of the specified Ethernet network. This API uses an asynchronous callback to return the result.|
| ohos.net.ethernet | function getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>): void | Obtains the network attributes of the specified Ethernet network. This API uses an asynchronous callback to return the result.|
| ohos.net.ethernet | function isIfaceActive(iface: string, callback: AsyncCallback\<number>): void | Checks whether the specified network port is active. This API uses an asynchronous callback to return the result.|
| ohos.net.ethernet | function getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void; | Obtains the list of all active network ports. This API uses an asynchronous callback to return the result.|
## Ethernet Connection – DHCP Mode
1. Use a network cable to connect the device to a network port.
2. Import the **ethernet** namespace from **@ohos.net.ethernet**.
3. Call **getAllActiveIfaces** to obtain the list of all active network ports, for example, **eth0** and **eth1**.
4. Call **isIfaceActive** in user mode to check whether the **eth0** port is active.
5. Call **getIfaceConfig** in user mode to obtain the static network attributes of the **eth0** port. By default, an unconfigured Ethernet network uses the DHCP mode, in which the Ethernet network obtains the automatically assigned network attributes.
```js
// Import the ethernet namespace from @ohos.net.ethernet.
import ethernet from '@ohos.net.ethernet'
// Call getAllActiveIfaces to obtain the list of all active network ports.
ethernet.getAllActiveIfaces((error, data) => {
if (error) {
console.log("getAllActiveIfaces callback error = " + error);
} else {
console.log("getAllActiveIfaces callback data.length = " + data.length);
for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces callback = " + data[i]);
}
}
});
// Call isIfaceActive to check whether the specified network port is active.
ethernet.isIfaceActive("eth0", (error, data) => {
if (error) {
console.log("isIfaceActive callback error = " + error);
} else {
console.log("isIfaceActive callback = " + data);
}
});
// Call getIfaceConfig to obtain the network attributes of the specified Ethernet network.
ethernet.getIfaceConfig("eth0", (error, data) => {
if (error) {
console.log("getIfaceConfig callback error = " + error);
} else {
console.log("getIfaceConfig callback mode = " + data.mode);
console.log("getIfaceConfig callback ipAddr = " + data.ipAddr);
console.log("getIfaceConfig callback routeAddr = " + data.routeAddr);
console.log("getIfaceConfig callback gateAddr = " + data.gateAddr);
console.log("getIfaceConfig callback maskAddr = " + data.maskAddr);
console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr);
console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr);
}
});
```
## Ethernet Connection – Static Mode
### How to Develop
1. Use a network cable to connect the device to a network port.
2. Import the **ethernet** namespace from **@ohos.net.ethernet**.
3. Call **getAllActiveIfaces** in user mode to obtain the list of all active network ports, for example, **eth0** and **eth1**.
4. Call **isIfaceActive** in user mode to check whether the **eth0** port is active.
5. Call **setIfaceConfig** in user mode to set the **eth0** port to the static mode, in which you need to manually assign the network attributes (including the IP address, subnet mask, gateway, and DNS).
6. Call **getIfaceConfig** in user mode to obtain the static network attributes of the **eth0** port.
```js
// Import the ethernet namespace from @ohos.net.ethernet.
import ethernet from '@ohos.net.ethernet'
// Call getAllActiveIfaces to obtain the list of all active network ports.
ethernet.getAllActiveIfaces((error, data) => {
if (error) {
console.log("getAllActiveIfaces callback error = " + error);
} else {
console.log("getAllActiveIfaces callback data.length = " + data.length);
for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces callback = " + data[i]);
}
}
});
// Call isIfaceActive to check whether the specified network port is active.
ethernet.isIfaceActive("eth0", (error, data) => {
if (error) {
console.log("isIfaceActive callback error = " + error);
} else {
console.log("isIfaceActive callback = " + data);
}
});
// Call setIfaceConfig to configure the network attributes of the specified Ethernet network.
ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.xx.xx", routeAddr:"192.168.xx.xx",
gateAddr:"192.168.xx.xx", maskAddr:"255.255.xx.xx", dnsAddr0:"1.1.xx.xx", dnsAddr1:"2.2.xx.xx"},(error) => {
if (error) {
console.log("setIfaceConfig callback error = " + error);
} else {
console.log("setIfaceConfig callback ok ");
}
});
// Call getIfaceConfig to obtain the network attributes of the specified Ethernet network.
ethernet.getIfaceConfig("eth0", (error, data) => {
if (error) {
console.log("getIfaceConfig callback error = " + error);
} else {
console.log("getIfaceConfig callback mode = " + data.mode);
console.log("getIfaceConfig callback ipAddr = " + data.ipAddr);
console.log("getIfaceConfig callback routeAddr = " + data.routeAddr);
console.log("getIfaceConfig callback gateAddr = " + data.gateAddr);
console.log("getIfaceConfig callback maskAddr = " + data.maskAddr);
console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr);
console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr);
}
});
```
...@@ -2,15 +2,19 @@ ...@@ -2,15 +2,19 @@
Network management functions include: Network management functions include:
- [HTTP Data Request](http-request.md): Initiates a data request through HTTP. - [HTTP data request](http-request.md): Initiates a data request through HTTP.
- [WebSocket Connection](websocket-connection.md): Establishes a bidirectional connection between the server and client through WebSocket. - [WebSocket connection](websocket-connection.md): Establishes a bidirectional connection between the server and client through WebSocket.
- [Socket Connection](socket-connection.md): Transmits data through Socket. - [Socket connection](socket-connection.md): Transmits data through Socket.
- [Network policy management](net-policy-management.md): Restricts network capabilities by setting network policies, including cellular network policy, sleep/power-saving mode policy, and background network policy, and resets network policies as needed.
- [Network sharing](net-sharing.md): Shares a device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing, and queries the network sharing state and shared mobile data volume.
- [Ethernet connection](net-ethernet.md): Provides wired network capabilities, which allow you to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network.
- [Network connection management](net-connection-manager.md): Provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution.
## Constraints ## Constraints
To use the functions of the network management module, you must obtain the permissions listed in the following table. To use the functions of the network management module, you must obtain the permissions listed in the following table.
| Permission | Description | | Permission | Description |
| -------------------------------- | -------------------------------------- | | -------------------------------- | -------------------------------------- |
| ohos.permission.GET_NETWORK_INFO | Allows an application to obtain the network connection information. | | ohos.permission.GET_NETWORK_INFO | Allows an application to obtain the network connection information. |
| ohos.permission.SET_NETWORK_INFO | Allows an application to modify the network connection state. | | ohos.permission.SET_NETWORK_INFO | Allows an application to modify the network connection state. |
......
# Network Sharing
## Introduction
The Network Sharing module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume.
> **NOTE**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-sharing.md).
## Basic Concepts
- Wi-Fi sharing: Shares the network through a Wi-Fi hotspot.
- Bluetooth sharing: Shares the network through Bluetooth.
- USB tethering: Shares the network using a USB flash drive.
## **Constraints**
- Programming language: C++ and JS
- System: Linux kernel
- 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.
## When to Use
Typical network sharing scenarios are as follows:
- Enabling network sharing
- Disabling network sharing
- Obtaining the data traffic of the shared network
The following describes the development procedure specific to each application scenario.
## Available APIs
For the complete list of APIs and example code, see [Network Sharing](../reference/apis/js-apis-net-sharing.md).
| Type| API| Description|
| ---- | ---- | ---- |
| ohos.net.sharing | function isSharingSupported(callback: AsyncCallback\<boolean>): void; | Checks whether the system supports network sharing. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function isSharing(callback: AsyncCallback\<boolean>): void; | Checks whether network sharing is active. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function startSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void; | Starts network sharing. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function stopSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void; | Stops network sharing. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getStatsRxBytes(callback: AsyncCallback\<number>): void; | Obtains the received data traffic during network sharing, in KB. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getStatsTxBytes(callback: AsyncCallback\<number>): void; | Obtains the sent data traffic during network sharing, in KB. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getStatsTotalBytes(callback: AsyncCallback\<number>): void; | Obtains the total data traffic during network sharing, in KB. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\<Array\<string>>): void; | Obtains the names of network interface cards (NICs) in the specified network sharing state.. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getSharingState(type: SharingIfaceType, callback: AsyncCallback\<SharingIfaceState>): void; | Obtains the network sharing state of the specified type. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\<Array\<string>>): void; | Obtains regular expressions of NICs of a specified type. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function on(type: 'sharingStateChange', callback: Callback\<boolean>): void; | Subscribes to network sharing state changes.|
| ohos.net.sharing | function off(type: 'sharingStateChange', callback?: Callback\<boolean>): void; | Unsubscribes from network sharing state changes.|
| ohos.net.sharing | unction on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void; | Subscribes to network sharing state changes of the specified NIC.|
| ohos.net.sharing | function off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void; | Unsubscribes from network sharing state changes of the specified NIC.|
| ohos.net.sharing | function on(type: 'sharingUpstreamChange', callback: Callback\<NetHandle>): void; | Subscribes to upstream NIC changes.|
| ohos.net.sharing | function off(type: 'sharingUpstreamChange', callback?: Callback\<NetHandle>): void; | Unsubscribes from upstream NIC changes.|
## Enabling Network Sharing
1. Import the **sharing** namespace from **@ohos.net.sharing**.
2. Subscribe to network sharing state changes.
3. Call **startSharing** to start network sharing of the specified type.
4. Return the callback for successfully starting network sharing.
```js
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes.
sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// Call startSharing to start network sharing of the specified type.
sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
```
## Disabling network sharing
### How to Develop
1. Import the **sharing** namespace from **@ohos.net.sharing**.
2. Subscribe to network sharing state changes.
3. Call **stopSharing** to stop network sharing of the specified type.
4. Return the callback for successfully stopping network sharing.
```js
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes.
sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// Call stopSharing to stop network sharing of the specified type.
sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
```
## Obtaining the data traffic of the shared network
### How to Develop
1. Import the **sharing** namespace from **@ohos.net.sharing**.
2. Call **startSharing** to start network sharing of the specified type.
3. Call **getStatsTotalBytes** to obtain the data traffic generated during data sharing.
4. Call **stopSharing** to stop network sharing of the specified type and clear the data volume of network sharing.
```js
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Call startSharing to start network sharing of the specified type.
sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
// Call getStatsTotalBytes to obtain the data traffic generated during data sharing.
sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// Call stopSharing to stop network sharing of the specified type and clear the data volume of network sharing.
sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
// Call getStatsTotalBytes again. The data volume of network sharing has been cleared.
sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
```
# Socket Connection # Socket Connection
## Introduction
## Use Cases The Socket Connection module allows an application to transmit data over a Socket connection through the TCP, UDP, or TLS protocol.
Your application can transmit data through Socket connections. Currently, the TCP and UDP protocols are supported. ## Basic Concepts
- Socket: An abstraction of endpoints for bidirectional communication between application processes running on different hosts in a network.
- TCP: Transmission Control Protocol, which is a byte stream–based transport layer communication protocol that is connection-oriented and reliable.
- UDP: User Datagram Protocol, which is a simple datagram-oriented transport layer communication protocol.
- TLS: Transport Layer Security, which is a protocol that ensures the data confidentiality and integrity between communication programs.
## When to Use
Applications transmit data over TCP, UDP, or TLS Socket connections. The main application scenarios are as follows:
- Implementing data transmission over TCP/UDP Socket connections
- Implementing encrypted data transmission over TLS Socket connections
## Available APIs ## Available APIs
The Socket connection function is mainly implemented by the Socket module. The following table describes the related APIs. For the complete list of APIs and example code, see [Socket Connection](../reference/apis/js-apis-socket.md).
Socket connection functions are mainly implemented by the **socket** module. The following table describes the related APIs.
| API| Description | | API| Description|
| -------- | -------- | | -------- | -------- |
| constructUDPSocketInstance() | Creates a **UDPSocket** object. | | constructUDPSocketInstance() | Creates a **UDPSocket** object.|
| constructTCPSocketInstance() | Creates a **TCPSocket** object. | | constructTCPSocketInstance() | Creates a **TCPSocket** object.|
| bind() | Binds the IP address and port number. | | bind() | Binds the IP address and port number.|
| send() | Sends data.| | send() | Sends data.|
| close() | Closes a Socket connection. | | close() | Closes a Socket connection.|
| getState() | Obtains the Socket connection status. | | getState() | Obtains the Socket connection status.|
| connect() | Connects to the specified IP address and port. This function is supported only for TCP. | | connect() | Connects to the specified IP address and port. This function is supported only for TCP.|
| getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API. | | getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API.|
| on(type:&nbsp;'message') | Enables listening for **message** events of the Socket connection. | | on(type:&nbsp;'message') | Subscribes to **message** events of the Socket connection.|
| off(type:&nbsp;'message') | Disables listening for **message** events of the Socket connection. | | off(type:&nbsp;'message') | Unsubscribes from **message** events of the Socket connection.|
| on(type:&nbsp;'close') | Enables listening for **close** events of the Socket connection. | | on(type:&nbsp;'close') | Subscribes to **close** events of the Socket connection.|
| off(type:&nbsp;'close') | Disables listening for **close** events of the Socket connection. | | off(type:&nbsp;'close') | Unsubscribes from **close** events of the Socket connection.|
| on(type:&nbsp;'error') | Enables listening for **error** events of the Socket connection. | | on(type:&nbsp;'error') | Subscribes to **error** events of the Socket connection.|
| off(type:&nbsp;'error') | Disables listening for **error** events of the Socket connection. | | off(type:&nbsp;'error') | Unsubscribes from **error** events of the Socket connection.|
| on(type:&nbsp;'listening') | Enables listening for **listening** events of the UDPSocket connection. | | on(type:&nbsp;'listening') | Subscribes to **listening** events of the UDP Socket connection. |
| off(type:&nbsp;'listening') | Disables listening for **listening** events of the UDPSocket connection. | | off(type:&nbsp;'listening') | Unsubscribes from **listening** events of the UDP Socket connection. |
| on(type:&nbsp;'connect') | Enables listening for **connect** events of the TCPSocket connection. | | on(type:&nbsp;'connect') | Subscribes to **connect** events of the TCP Socket connection. |
| off(type:&nbsp;'connect') | Disables listening for **connect** events of the TCPSocket connection. | | off(type:&nbsp;'connect') | Unsubscribes from **connect** events of the TCP Socket connection.|
TLS Socket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs.
| API| Description|
| -------- | -------- |
| bind() | Binds the IP address and port number.|
| close(type:&nbsp;'error') | Closes a Socket connection.|
| connect() | Sets up a connection to the specified IP address and port number.|
| getCertificate() | Obtains an object representing the local certificate.|
| getCipherSuite() | Obtains a list containing information about the negotiated cipher suite.|
| getProtocol() | Obtains a string containing the SSL/TLS protocol version negotiated for the current connection.|
| getRemoteAddress() | Obtains the peer address of the TLS Socket connection.|
| getRemoteCertificate() | Obtains an object representing a peer certificate.|
| getSignatureAlgorithms() | Obtains a list containing signature algorithms shared between the server and client, in descending order of priority.|
| getState() | Obtains the TLS Socket connection status.|
| off(type:&nbsp;'close') | Unsubscribes from **close** events of the TLS Socket connection.|
| off(type:&nbsp;'error') | Unsubscribes from **error** events of the TLS Socket connection.|
| off(type:&nbsp;'message') | Unsubscribes from **message** events of the TLS Socket connection.|
| on(type:&nbsp;'close') | Subscribes to **close** events of the TLS Socket connection.|
| on(type:&nbsp;'error') | Subscribes to **error** events of the TLS Socket connection.|
| on(type:&nbsp;'message') | Subscribes to **message** events of the TLS Socket connection.|
| send() | Sends data.|
| setExtraOptions() | Sets other properties of the TLS Socket connection.|
## How to Develop ## Transmitting Data over TCP/UDP Socket Connections
The implementation is similar for UDPSocket and TCPSocket. The following uses the TCPSocket as an example. The implementation is similar for UDP Socket and TCP Socket connections. The following uses data transmission over a TCP Socket connection as an example.
1. Import the required Socket module. 1. Import the required **socket** module.
2. Create a **TCPSocket** object. 2. Create a **TCPSocket** object.
3. (Optional) Enable listening for TCPSocket events. 3. (Optional) Subscribe to TCP Socket connection events.
4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system. 4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system.
...@@ -48,15 +84,15 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -48,15 +84,15 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
6. Send data. 6. Send data.
7. Enable the TCPSocket connection to be automatically closed after use. 7. Enable the TCP Socket connection to be automatically closed after use.
```js ```js
import socket from '@ohos.net.socket' import socket from '@ohos.net.socket'
// Create a TCPSocket object. // Create a TCPSocket object.
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
// Enable listening for TCPSocket events. // Subscribe to TCP Socket connection events.
tcp.on('message', value => { tcp.on('message', value => {
console.log("on message") console.log("on message")
let buffer = value.message let buffer = value.message
...@@ -73,7 +109,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -73,7 +109,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
tcp.on('close', () => { tcp.on('close', () => {
console.log("on close") console.log("on close")
}); });
// Bind the local IP address and port number. // Bind the local IP address and port number.
let bindAddress = { let bindAddress = {
address: '192.168.xx.xx', address: '192.168.xx.xx',
...@@ -86,6 +122,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -86,6 +122,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
return; return;
} }
console.log('bind success'); console.log('bind success');
// Set up a connection to the specified IP address and port number. // Set up a connection to the specified IP address and port number.
let connectAddress = { let connectAddress = {
address: '192.168.xx.xx', address: '192.168.xx.xx',
...@@ -100,6 +137,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -100,6 +137,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
return; return;
} }
console.log('connect success'); console.log('connect success');
// Send data. // Send data.
tcp.send({ tcp.send({
data: 'Hello, server!' data: 'Hello, server!'
...@@ -112,7 +150,8 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -112,7 +150,8 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
}) })
}); });
}); });
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket events.
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
setTimeout(() => { setTimeout(() => {
tcp.close((err) => { tcp.close((err) => {
console.log('close socket.') console.log('close socket.')
...@@ -122,3 +161,167 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -122,3 +161,167 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
tcp.off('close'); tcp.off('close');
}, 30 * 1000); }, 30 * 1000);
``` ```
## Implementing Encrypted Data Transmission over TLS Socket Connections
### How to Develop
TLS Socket connection process on the client:
1. Import the required **socket** module.
2. Bind the IP address and port number of the server.
3. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate.
4. Create a **TLSSocket** object.
5. (Optional) Subscribe to TLS Socket connection events.
6. Send data.
7. Enable the TLS Socket connection to be automatically closed after use.
```js
import socket from '@ohos.net.socket'
// Create a TLS Socket connection (for two-way authentication).
let tlsTwoWay = socket.constructTLSSocketInstance();
// Subscribe to TLS Socket connection events.
tcp.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0; i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tcp.on('connect', () => {
console.log("on connect")
});
tcp.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
// Set the communication parameters.
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
// Set up a connection to the specified IP address and port number.
address: {
address: "192.168.xx.xxx",
port: xxxx, // Port
family: 1,
},
// Set the parameters used for authentication during communication.
secureOptions: {
key: "xxxx", // Key
cert: "xxxx", // Digital certificate
ca: ["xxxx"], // CA certificate
passwd: "xxxx", // Password for generating the key
protocols: [socket.Protocol.TLSv12], // Communication protocol
useRemoteCipherPrefer: true, // Whether to preferentially use the peer cipher suite
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // Signature algorithm
cipherSuite: "AES256-SHA256", // Cipher suite
},
};
// Set up a connection.
tlsTwoWay.connect(options, (err, data) => {
console.error(err);
console.log(data);
});
// Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events.
tls.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tls.off('message');
tls.off('connect');
tls.off('close');
});
// Create a TLS Socket connection (for one-way authentication).
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// Subscribe to TLS Socket connection events.
tcp.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0;i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tcp.on('connect', () => {
console.log("on connect")
});
tcp.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
// Set the communication parameters.
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"], // CA certificate
cipherSuite: "AES256-SHA256", // Cipher suite
},
};
// Set up a connection.
tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err);
console.log(data);
});
// Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events.
tls.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tls.off('message');
tls.off('connect');
tls.off('close');
});
```
## Samples
The following samples are provided to help you better understand how to develop Socket connection features:
- [`Socket`: Socket Connection (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket)
- [UDP Socket (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH)
- [TCP Socket (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo)
...@@ -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.
......
...@@ -13,7 +13,7 @@ For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis ...@@ -13,7 +13,7 @@ For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis
| API | Description | | API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KvManager** object for database management. | | createKVManager(config: KVManagerConfig): KVManager | Creates a **KvManager** object for database management. |
| getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Creates and obtains a KV store.| | getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Creates and obtains a KV store.|
| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array\|string\|number\|boolean): Promise&lt;void> | Inserts and updates data. | | put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array\|string\|number\|boolean): Promise&lt;void> | Inserts and updates data. |
| delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. | | delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. |
...@@ -117,16 +117,10 @@ The following uses a single KV store as an example to describe the development p ...@@ -117,16 +117,10 @@ The following uses a single KV store as an example to describe the development p
bundleName: 'com.example.datamanagertest', bundleName: 'com.example.datamanagertest',
context:context, context:context,
} }
distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) { kvManager = distributedKVStore.createKVManager(kvManagerConfig);
if (err) { console.log("Created KVManager successfully");
console.error(`Failed to create KVManager. code is ${err.code},message is ${err.message}`);
return;
}
console.log('Created KVManager successfully');
kvManager = manager;
});
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`Failed to create KVManager. Code is ${e.code}, message is ${e.message}`);
} }
``` ```
...@@ -150,14 +144,14 @@ The following uses a single KV store as an example to describe the development p ...@@ -150,14 +144,14 @@ The following uses a single KV store as an example to describe the development p
}; };
kvManager.getKVStore('storeId', options, function (err, store) { kvManager.getKVStore('storeId', options, function (err, store) {
if (err) { if (err) {
console.error(`Failed to get KVStore: code is ${err.code},message is ${err.message}`); console.error(`Failed to get KVStore: code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.log('Obtained KVStore successfully'); console.log('Obtained KVStore successfully');
kvStore = store; kvStore = store;
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred. Code is ${e.code}, message is ${e.message}`);
} }
``` ```
...@@ -175,7 +169,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -175,7 +169,7 @@ The following uses a single KV store as an example to describe the development p
console.log(`dataChange callback call data: ${data}`); console.log(`dataChange callback call data: ${data}`);
}); });
}catch(e){ }catch(e){
console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occured. Code is ${e.code}, message is ${e.message}`);
} }
``` ```
...@@ -192,13 +186,13 @@ The following uses a single KV store as an example to describe the development p ...@@ -192,13 +186,13 @@ The following uses a single KV store as an example to describe the development p
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
if (err != undefined) { if (err != undefined) {
console.error(`Failed to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put data. Code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.log('Put data successfully'); console.log("Put data successfully");
}); });
}catch (e) { }catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred. Code is ${e.code}, message is ${e.message}`);
} }
``` ```
...@@ -215,20 +209,20 @@ The following uses a single KV store as an example to describe the development p ...@@ -215,20 +209,20 @@ The following uses a single KV store as an example to describe the development p
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
if (err != undefined) { if (err != undefined) {
console.error(`Failed to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put data. Code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.log('Put data successfully'); console.log("Put data successfully");
kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) { kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) {
if (err != undefined) { if (err != undefined) {
console.error(`Failed to get data.code is ${err.code},message is ${err.message}`); console.error(`Failed to obtain data. Code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.log(`Obtained data successfully:${data}`); console.log(`Obtained data successfully:${data}`);
}); });
}); });
}catch (e) { }catch (e) {
console.error(`Failed to get.code is ${e.code},message is ${e.message}`); console.error(`Failed to obtain data. Code is ${e.code}, message is ${e.message}`);
} }
``` ```
...@@ -262,7 +256,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -262,7 +256,7 @@ The following uses a single KV store as an example to describe the development p
// 1000 indicates that the maximum delay is 1000 ms. // 1000 indicates that the maximum delay is 1000 ms.
kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000); kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000);
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred. code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred. Code is ${e.code}, message is ${e.message}`);
} }
} }
}); });
......
...@@ -114,21 +114,19 @@ You can use the following APIs to delete a **Preferences** instance or data file ...@@ -114,21 +114,19 @@ You can use the following APIs to delete a **Preferences** instance or data file
```ts ```ts
// Obtain the context. // Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
let preferences = null; let preferences = null;
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage) {
context = this.context; let promise = data_preferences.getPreferences(this.context, 'mystore');
promise.then((pref) => {
preferences = pref;
}).catch((err) => {
console.info("Failed to get the preferences.");
})
} }
} }
let promise = data_preferences.getPreferences(context, 'mystore');
promise.then((pref) => {
preferences = pref;
}).catch((err) => {
console.info("Failed to get the preferences.");
})
``` ```
3. Write data. 3. Write data.
......
# Device # Device Management
- USB Service
- [USB Service Overview](usb-overview.md)
- [USB Service Development](usb-guidelines.md)
- Location - Location
- [Location Service Development](location-guidelines.md) - [Location Service Development](location-guidelines.md)
- Multimodal Input
- [Input Device Development](inputdevice-guidelines.md)
- [Mouse Pointer Development](pointerstyle-guidelines.md)
- Sensor - Sensor
- [Sensor Overview](sensor-overview.md) - [Sensor Overview](sensor-overview.md)
- [Sensor Development](sensor-guidelines.md) - [Sensor Development](sensor-guidelines.md)
- Vibrator
- [Vibrator Overview](vibrator-overview.md)
- [Vibrator Development](vibrator-guidelines.md)
- Multimodal Input
- [Input Device Development](inputdevice-guidelines.md)
- [Mouse Pointer Development](pointerstyle-guidelines.md)
- Update Service - Update Service
- [Sample Server Overview](sample-server-overview.md) - [Sample Server Overview](sample-server-overview.md)
- [Sample Server Development](sample-server-guidelines.md) - [Sample Server Development](sample-server-guidelines.md)
- USB Service - Stationary
- [USB Service Overview](usb-overview.md) - [Stationary Development](stationary-guidelines.md)
- [USB Service Development](usb-guidelines.md)
- Vibrator
- [Vibrator Overview](vibrator-overview.md)
- [Vibrator Development](vibrator-guidelines.md)
\ No newline at end of file
...@@ -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`)}`);
}
}); });
``` ```
# Stationary Development
## When to Use
An application can call the **Stationary** module to obtain the device status, for example, whether the device is absolutely or relatively still.
For details about the APIs, see [Stationary](../reference/apis/js-apis-stationary.md).
## Device Status Type Parameters
| Name| Description|
| -------- | -------- |
| still | Absolutely still.|
| relativeStill | Relatively still.|
## Parameters for Subscribing to Device Status events
| Name | Value | Description |
| ------------------------------ | ---- | ---------------------------------------- |
| ENTER | 1 | Event indicating entering device status. |
| EXIT | 2 | Event indicating exiting device status.|
| ENTER_EXIT | 3 | Event indicating entering and exiting device status.|
## Returned Device Status Parameters
| Name | Value | Description |
| ------------------------------ | ---- | ---------------------------------------- |
| ENTER | 1 | Entering device status. |
| EXIT | 2 | Exiting device status.|
## Available APIs
| Module | Name | Description |
| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ohos.stationary | on(activity: ActivityType, event: ActivityEvent, reportLatencyNs: number, callback: Callback&lt;ActivityResponse&gt;): void | Subscribes to the device status. This API uses an asynchronous callback to return the result.|
| ohos.stationary | once(activity: ActivityType, callback: Callback&lt;ActivityResponse&gt;): void | Obtains the device status. This API uses an asynchronous callback to return the result.|
| ohos.stationary | off(activity: ActivityType, event: ActivityEvent, callback?: Callback&lt;ActivityResponse&gt;): void | Unsubscribes from the device status. |
## Constraints
The device must support the acceleration sensor.
## How to Develop
1. Subscribe to the event indicating entering the absolute still state, and the event is reported every 1 second.
```js
import stationary from '@ohos.stationary';
var reportLatencyNs = 1000000000;
try {
stationary.on('still', stationary.ActivityEvent.ENTER, reportLatencyNs, (data) => {
console.log('data='+ JSON.stringify(data));
})
} catch (err) {
console.error('errCode: ' + err.code + ' ,msg: ' + err.message);
}
```
2. Obtain the event indicating entering the absolute still state.
```js
import stationary from '@ohos.stationary';
try {
stationary.once('still', (data) => {
console.log('data='+ JSON.stringify(data));
})
} catch (err) {
console.error('errCode: ' + err.code + ' ,msg: ' + err.message);
}
```
3. Unsubscribe from the event indicating entering the absolute still state.
```js
import stationary from '@ohos.stationary';
try {
stationary.off('still', stationary.ActivityEvent.ENTER, (data) => {
console.log('data='+ JSON.stringify(data));
})
} catch (err) {
console.error('errCode: ' + err.code + ' ,msg: ' + err.message);
}
```
...@@ -16,6 +16,10 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md ...@@ -16,6 +16,10 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
| ohos.vibrator | startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback&lt;void&gt;): void | Starts vibration with the specified effect and attribute. This API uses an asynchronous callback to return the result.| | ohos.vibrator | startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback&lt;void&gt;): void | Starts vibration with the specified effect and attribute. This API uses an asynchronous callback to return the result.|
| ohos.vibrator | stopVibration(stopMode: VibratorStopMode): Promise&lt;void&gt; | Stops vibration in the specified mode. This API uses a promise to return the result. | | ohos.vibrator | stopVibration(stopMode: VibratorStopMode): Promise&lt;void&gt; | Stops vibration in the specified mode. This API uses a promise to return the result. |
| ohos.vibrator | stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback&lt;void&gt;): void | Stops vibration in the specified mode. This API uses an asynchronous callback to return the result. | | ohos.vibrator | stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback&lt;void&gt;): void | Stops vibration in the specified mode. This API uses an asynchronous callback to return the result. |
| ohos.vibrator | stopVibration(): Promise&lt;void&gt; | Stops vibration in all modes. This API uses a promise to return the result. |
| ohos.vibrator | stopVibration(callback: AsyncCallback&lt;void&gt;): void | Stops vibration in all modes. This API uses an asynchronous callback to return the result. |
| ohos.vibrator | isSupportEffect(effectId: string): Promise&lt;boolean&gt; | Checks whether the passed effect ID is supported. This API uses a promise to return the result. The value **true** means that the passed effect ID is supported, and **false** means the opposite. |
| ohos.vibrator | isSupportEffect(effectId: string, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether the passed effect ID is supported. This API uses an asynchronous callback to return the result. The value **true** means that the passed effect ID is supported, and **false** means the opposite. |
## How to Develop ## How to Develop
...@@ -27,7 +31,7 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md ...@@ -27,7 +31,7 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
```js ```js
import vibrator from '@ohos.vibrator'; import vibrator from '@ohos.vibrator';
try { try {
vibrator.startVibration({ vibrator.startVibration({ // To use startVibration, you must configure the ohos.permission.VIBRATE permission.
type: 'time', type: 'time',
duration: 1000, duration: 1000,
}, { }, {
...@@ -50,7 +54,7 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md ...@@ -50,7 +54,7 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
```js ```js
import vibrator from '@ohos.vibrator'; import vibrator from '@ohos.vibrator';
try { try {
// Stop vibration in VIBRATOR_STOP_MODE_TIME mode. // Stop vibration in VIBRATOR_STOP_MODE_TIME mode. To use stopVibration, you must configure the ohos.permission.VIBRATE permission.
vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, function (error) { vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, function (error) {
if (error) { if (error) {
console.log('error.code' + error.code + 'error.message' + error.message); console.log('error.code' + error.code + 'error.message' + error.message);
...@@ -62,3 +66,72 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md ...@@ -62,3 +66,72 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
console.info('errCode: ' + err.code + ' ,msg: ' + err.message); console.info('errCode: ' + err.code + ' ,msg: ' + err.message);
} }
``` ```
4. Stop vibration in all modes.
```js
import vibrator from '@ohos.vibrator';
// To use startVibration and stopVibration, you must configure the ohos.permission.VIBRATE permission.
try {
vibrator.startVibration({
type: 'time',
duration: 1000,
}, {
id: 0,
usage: 'alarm'
}, (error) => {
if (error) {
console.error('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message);
return;
}
console.log('Callback returned to indicate a successful vibration.');
});
// Stop vibration in all modes.
vibrator.stopVibration(function (error) {
if (error) {
console.log('error.code' + error.code + 'error.message' + error.message);
return;
}
console.log('Callback returned to indicate successful.');
})
} catch (error) {
console.info('errCode: ' + error.code + ' ,msg: ' + error.message);
}
```
5. Check whether the passed effect ID is supported.
```js
import vibrator from '@ohos.vibrator';
try {
// Check whether 'haptic.clock.timer' is supported.
vibrator.isSupportEffect('haptic.clock.timer', function (err, state) {
if (err) {
console.error('isSupportEffect failed, error:' + JSON.stringify(err));
return;
}
console.log('The effectId is ' + (state ? 'supported' : 'unsupported'));
if (state) {
try {
vibrator.startVibration({ // To use startVibration, you must configure the ohos.permission.VIBRATE permission.
type: 'preset',
effectId: 'haptic.clock.timer',
count: 1,
}, {
usage: 'unknown'
}, (error) => {
if(error) {
console.error('haptic.clock.timer vibrator error:' + JSON.stringify(error));
} else {
console.log('haptic.clock.timer vibrator success');
}
});
} catch (error) {
console.error('Exception in, error:' + JSON.stringify(error));
}
}
})
} catch (error) {
console.error('Exception in, error:' + JSON.stringify(error));
}
```
# DFX # DFX
- Application Event Logging - [Development of Application Event Logging](hiappevent-guidelines.md)
- [Development of Application Event Logging](hiappevent-guidelines.md) - [Development of Performance Tracing](hitracemeter-guidelines.md)
- Distributed Call Chain Tracing - [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md)
- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md) - [HiLog Development (Native)](hilog-guidelines.md)
- HiLog
- [HiLog Development](hilog-guidelines.md)
- Performance Tracing
- [Development of Performance Tracing](hitracemeter-guidelines.md)
- Error Management - Error Management
- [Development of Error Manager](errormanager-guidelines.md) - [Development of Error Manager](errormanager-guidelines.md)
- [Development of Application Recovery](apprecovery-guidelines.md) - [Development of Application Recovery](apprecovery-guidelines.md)
\ No newline at end of file
...@@ -12,11 +12,11 @@ Application error management APIs are provided by the **errorManager** module. F ...@@ -12,11 +12,11 @@ Application error management APIs are provided by the **errorManager** module. F
| API | Description | | API | Description |
| ------------------------------------------------------------ | ---------------------------------------------------- | | ------------------------------------------------------------ | ---------------------------------------------------- |
| registerErrorObserver(observer: ErrorObserver): number | Registers an observer for application errors. A callback will be invoked when an application error is detected. This API works in a synchronous manner. The return value is the SN of the registered observer.| | on(type: "error", observer: ErrorObserver): number | Registers an observer for application errors. A callback will be invoked when an application error is detected. This API works in a synchronous manner. The return value is the SN of the registered observer.|
| unregisterErrorObserver(observerId: number, callback: AsyncCallback\<void\>): void | Unregisters an observer in callback mode. The number passed to this API is the SN of the registered observer. | | off(type: "error", observerId: number, callback: AsyncCallback\<void\>): void | Unregisters an observer in callback mode. The number passed to this API is the SN of the registered observer. |
| unregisterErrorObserver(observerId: number): Promise\<void\> | Unregisters an observer in promise mode. The number passed to this API is the SN of the registered observer. | | off(type: "error", observerId: number): Promise\<void\> | Unregisters an observer in promise mode. The number passed to this API is the SN of the registered observer. |
When an asynchronous callback is used, the return value can be processed directly in the callback. If a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Result Codes for Unregistering an Observer](#result-codes-for-unregistering-an-observer). When an asynchronous callback is used, the return value can be processed directly in the callback. If a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Result Codes for Unregistering an Observer](#result codes-for-unregistering-an-observer).
**Table 2** Description of the ErrorObserver API **Table 2** Description of the ErrorObserver API
...@@ -39,22 +39,23 @@ When an asynchronous callback is used, the return value can be processed directl ...@@ -39,22 +39,23 @@ When an asynchronous callback is used, the return value can be processed directl
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import errorManager from '@ohos.app.ability.errorManager'; import errorManager from '@ohos.app.ability.errorManager';
var registerId = -1; let registerId = -1;
var callback = { let callback = {
onUnhandledException: function (errMsg) { onUnhandledException: function (errMsg) {
console.log(errMsg); console.log(errMsg);
} }
} }
export default class EntryAbility extends Ability {
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
console.log("[Demo] EntryAbility onCreate") console.log("[Demo] EntryAbility onCreate")
registerId = errorManager.registerErrorObserver(callback); registerId = errorManager.on("error", callback);
globalThis.abilityWant = want; globalThis.abilityWant = want;
} }
onDestroy() { onDestroy() {
console.log("[Demo] EntryAbility onDestroy") console.log("[Demo] EntryAbility onDestroy")
errorManager.unregisterErrorObserver(registerId, (result) => { errorManager.off("error", registerId, (result) => {
console.log("[Demo] result " + result.code + ";" + result.message) console.log("[Demo] result " + result.code + ";" + result.message)
}); });
} }
......
...@@ -136,7 +136,7 @@ async function copySandbox2Public() { ...@@ -136,7 +136,7 @@ async function copySandbox2Public() {
console.error('file asset get failed, message = ' + err); console.error('file asset get failed, message = ' + err);
} }
let fdPub = await fileAsset.open('rw'); let fdPub = await fileAsset.open('rw');
let fdSand = await fs.open(sandboxDirPath + 'testFile.txt', OpenMode.READ_WRITE); let fdSand = await fs.open(sandboxDirPath + 'testFile.txt', fs.OpenMode.READ_WRITE);
await fs.copyFile(fdSand.fd, fdPub); await fs.copyFile(fdSand.fd, fdPub);
await fileAsset.close(fdPub); await fileAsset.close(fdPub);
await fs.close(fdSand.fd); await fs.close(fdSand.fd);
...@@ -174,7 +174,7 @@ async function example() { ...@@ -174,7 +174,7 @@ async function example() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS); const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then((asset) => { media.createAsset(mediaType, "testFile.txt", path).then((asset) => {
console.info("createAsset successfully:" + JSON.stringify(asset)); console.info("createAsset successfully:" + JSON.stringify(asset));
}).catch((err) => { }).catch((err) => {
console.error("createAsset failed with error: " + err); console.error("createAsset failed with error: " + err);
......
...@@ -42,14 +42,11 @@ async function example() { ...@@ -42,14 +42,11 @@ async function example() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
fetchFileResult.getFirstObject().then((fileAsset) => { fetchFileResult.getFirstObject().then(async (fileAsset) => {
console.log('getFirstObject.displayName : ' + fileAsset.displayName); console.log('getFirstObject.displayName : ' + fileAsset.displayName);
for (let i = 1; i < fetchFileResult.getCount(); i++) { for (let i = 1; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject().then((fileAsset) => { let fileAsset = await fetchFileResult.getNextObject();
console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
}).catch((err) => {
console.error('Failed to get next object: ' + err);
});
} }
}).catch((err) => { }).catch((err) => {
console.error('Failed to get first object: ' + err); console.error('Failed to get first object: ' + err);
...@@ -75,14 +72,11 @@ async function example() { ...@@ -75,14 +72,11 @@ async function example() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
fetchFileResult.getFirstObject().then((fileAsset) => { fetchFileResult.getFirstObject().then(async (fileAsset) => {
console.info('getFirstObject.displayName : ' + fileAsset.displayName); console.info('getFirstObject.displayName : ' + fileAsset.displayName);
for (let i = 1; i < fetchFileResult.getCount(); i++) { for (let i = 1; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject().then((fileAsset) => { let fileAsset = await fetchFileResult.getNextObject();
console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
}).catch((err) => {
console.error('Failed to get next object: ' + err);
});
} }
}).catch((err) => { }).catch((err) => {
console.error('Failed to get first object: ' + err); console.error('Failed to get first object: ' + err);
...@@ -108,14 +102,11 @@ async function example() { ...@@ -108,14 +102,11 @@ async function example() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
fetchFileResult.getFirstObject().then((fileAsset) => { fetchFileResult.getFirstObject().then(async (fileAsset) => {
console.info('getFirstObject.displayName : ' + fileAsset.displayName); console.info('getFirstObject.displayName : ' + fileAsset.displayName);
for (let i = 1; i < fetchFileResult.getCount(); i++) { for (let i = 1; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject().then((fileAsset) => { let fileAsset = await fetchFileResult.getNextObject();
console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
}).catch((err) => {
console.error('Failed to get next object: ' + err);
});
} }
}).catch((err) => { }).catch((err) => {
console.error('Failed to get first object: ' + err); console.error('Failed to get first object: ' + err);
......
...@@ -6,7 +6,7 @@ The [intl](intl-guidelines.md) module provides basic i18n capabilities through t ...@@ -6,7 +6,7 @@ The [intl](intl-guidelines.md) module provides basic i18n capabilities through t
## Obtaining and Setting i18n Information ## Obtaining and Setting i18n Information
The system provides APIs to configure information such as the system language, preferred language, country or region, 24-hour clock, and local digit switch. The following table lists the APIs used to configure information such as the system language, preferred language, country or region, 24-hour clock, and use of local digits.
### Available APIs ### Available APIs
...@@ -30,15 +30,15 @@ The system provides APIs to configure information such as the system language, p ...@@ -30,15 +30,15 @@ The system provides APIs to configure information such as the system language, p
| System | getPreferredLanguageList()<sup>9+</sup> | Obtains the preferred language list. | | System | getPreferredLanguageList()<sup>9+</sup> | Obtains the preferred language list. |
| System | getFirstPreferredLanguage()<sup>9+</sup> | Obtains the first language in the preferred language list. | | System | getFirstPreferredLanguage()<sup>9+</sup> | Obtains the first language in the preferred language list. |
| System | getAppPreferredLanguage()<sup>9+</sup> | Obtains the preferred language of an application. | | System | getAppPreferredLanguage()<sup>9+</sup> | Obtains the preferred language of an application. |
| System | setUsingLocalDigit(flag: boolean)<sup>9+</sup> | Sets whether to enable the local digit switch. | | System | setUsingLocalDigit(flag: boolean)<sup>9+</sup> | Specifies whether to enable use of local digits. |
| System | getUsingLocalDigit()<sup>9+</sup> | Checks whether the local digit switch is turned on. | | System | getUsingLocalDigit()<sup>9+</sup> | Checks whether use of local digits is enabled. |
| | isRTL(locale:string):boolean<sup>9+</sup> | Checks whether the locale uses a right-to-left (RTL) language.| | | isRTL(locale:string):boolean<sup>9+</sup> | Checks whether the locale uses a right-to-left (RTL) language.|
### How to Develop ### How to Develop
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Obtain and set the system language. 2. Obtain and set the system language.
...@@ -51,7 +51,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -51,7 +51,7 @@ The system provides APIs to configure information such as the system language, p
I18n.System.setSystemLanguage("en"); // Set the system language to en. I18n.System.setSystemLanguage("en"); // Set the system language to en.
let language = I18n.System.getSystemLanguage(); // language = "en" let language = I18n.System.getSystemLanguage(); // language = "en"
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -65,7 +65,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -65,7 +65,7 @@ The system provides APIs to configure information such as the system language, p
I18n.System.setSystemRegion("CN"); // Set the system country to CN. I18n.System.setSystemRegion("CN"); // Set the system country to CN.
let region = I18n.System.getSystemRegion(); // region = "CN" let region = I18n.System.getSystemRegion(); // region = "CN"
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -79,7 +79,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -79,7 +79,7 @@ The system provides APIs to configure information such as the system language, p
I18n.System.setSystemLocale("zh-Hans-CN"); // Set the system locale to zh-Hans-CN. I18n.System.setSystemLocale("zh-Hans-CN"); // Set the system locale to zh-Hans-CN.
let locale = I18n.System.getSystemLocale(); // locale = "zh-Hans-CN" let locale = I18n.System.getSystemLocale(); // locale = "zh-Hans-CN"
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -92,7 +92,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -92,7 +92,7 @@ The system provides APIs to configure information such as the system language, p
let rtl = I18n.isRTL("zh-CN"); // rtl = false let rtl = I18n.isRTL("zh-CN"); // rtl = false
rtl = I18n.isRTL("ar"); // rtl = true rtl = I18n.isRTL("ar"); // rtl = true
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -106,7 +106,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -106,7 +106,7 @@ The system provides APIs to configure information such as the system language, p
I18n.System.set24HourClock(true); I18n.System.set24HourClock(true);
let hourClock = I18n.System.is24HourClock(); // hourClock = true let hourClock = I18n.System.is24HourClock(); // hourClock = true
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -121,7 +121,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -121,7 +121,7 @@ The system provides APIs to configure information such as the system language, p
let sentenceCase = false; let sentenceCase = false;
let localizedLanguage = I18n.System.getDisplayLanguage(language, locale, sentenceCase); // localizedLanguage = "English" let localizedLanguage = I18n.System.getDisplayLanguage(language, locale, sentenceCase); // localizedLanguage = "English"
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -136,7 +136,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -136,7 +136,7 @@ The system provides APIs to configure information such as the system language, p
let sentenceCase = false; let sentenceCase = false;
let localizedCountry = I18n.System.getDisplayCountry(country, locale, sentenceCase); // localizedCountry = "U.S." let localizedCountry = I18n.System.getDisplayCountry(country, locale, sentenceCase); // localizedCountry = "U.S."
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -150,7 +150,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -150,7 +150,7 @@ The system provides APIs to configure information such as the system language, p
let languageList = I18n.System.getSystemLanguages(); // languageList = ["en-Latn-US", "zh-Hans"] let languageList = I18n.System.getSystemLanguages(); // languageList = ["en-Latn-US", "zh-Hans"]
let countryList = I18n.System.getSystemCountries("zh"); // countryList = ["ZW", "YT", ..., "CN", "DE"], 240 countries and regions in total let countryList = I18n.System.getSystemCountries("zh"); // countryList = ["ZW", "YT", ..., "CN", "DE"], 240 countries and regions in total
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -162,7 +162,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -162,7 +162,7 @@ The system provides APIs to configure information such as the system language, p
try { try {
let isSuggest = I18n.System.isSuggested("zh", "CN"); // isSuggest = true let isSuggest = I18n.System.isSuggested("zh", "CN"); // isSuggest = true
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -182,7 +182,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -182,7 +182,7 @@ The system provides APIs to configure information such as the system language, p
let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // firstPreferredLanguage = "en-GB" let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // firstPreferredLanguage = "en-GB"
let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Set the preferred language of the application to en-GB if the application contains en-GB resources. let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Set the preferred language of the application to en-GB if the application contains en-GB resources.
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -190,14 +190,14 @@ The system provides APIs to configure information such as the system language, p ...@@ -190,14 +190,14 @@ The system provides APIs to configure information such as the system language, p
Call **setUsingLocalDigit** to enable the local digit switch. (This is a system API and can be called only by system applications with the UPDATE_CONFIGURATION permission.) Call **setUsingLocalDigit** to enable the local digit switch. (This is a system API and can be called only by system applications with the UPDATE_CONFIGURATION permission.)
Call **getUsingLocalDigit** to check whether the local digit switch is enabled. Call **getUsingLocalDigit** to check whether the local digit switch is enabled.
Currently, the local digit switch applies only to the following languages: "ar", "as", "bn", "fa", "mr", "my", "ne", and "ur". Currently, use of local digits is supported only for the following languages: **ar**, **as**, **bn**, **fa**, **mr**, **my**, **ne**, **ur**.
```js ```js
try { try {
I18n.System.setUsingLocalDigit(true); // Enable the local digit switch. I18n.System.setUsingLocalDigit(true); // Enable the local digit switch.
let status = I18n.System.getUsingLocalDigit(); // status = true let status = I18n.System.getUsingLocalDigit(); // status = true
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -220,14 +220,14 @@ try { ...@@ -220,14 +220,14 @@ try {
| Calendar | getMinimalDaysInFirstWeek():number<sup>8+</sup> | Obtains the minimum number of days in the first week of a year. | | Calendar | getMinimalDaysInFirstWeek():number<sup>8+</sup> | Obtains the minimum number of days in the first week of a year. |
| Calendar | setMinimalDaysInFirstWeek(value:number): void<sup>8+</sup> | Sets the minimum number of days in the first week of a year. | | Calendar | setMinimalDaysInFirstWeek(value:number): void<sup>8+</sup> | Sets the minimum number of days in the first week of a year. |
| Calendar | getDisplayName(locale:string):string<sup>8+</sup> | Obtains the localized display of the **Calendar** object. | | Calendar | getDisplayName(locale:string):string<sup>8+</sup> | Obtains the localized display of the **Calendar** object. |
| Calendar | isWeekend(date?:Date):boolean<sup>8+</sup> | Checks whether the specified date in this **Calendar** object is a weekend. | | Calendar | isWeekend(date?:Date):boolean<sup>8+</sup> | Checks whether a given date is a weekend in the calendar. |
### How to Develop ### How to Develop
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Instantiate a **Calendar** object. 2. Instantiate a **Calendar** object.
...@@ -254,7 +254,7 @@ try { ...@@ -254,7 +254,7 @@ try {
Call **set** to set the year, month, day, hour, minute, and second for the **Calendar** object. Call **set** to set the year, month, day, hour, minute, and second for the **Calendar** object.
```js ```js
calendar.set(2021, 12, 21, 6, 0, 0) calendar.set(2021, 12, 21, 6, 0, 0);
``` ```
5. Set and obtain the time zone for the **Calendar** object. 5. Set and obtain the time zone for the **Calendar** object.
...@@ -317,7 +317,7 @@ try { ...@@ -317,7 +317,7 @@ try {
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Instantiate a **PhoneNumberFormat** object. 2. Instantiate a **PhoneNumberFormat** object.
...@@ -359,7 +359,7 @@ The **I18NUtil** class provides an API to implement measurement conversion. ...@@ -359,7 +359,7 @@ The **I18NUtil** class provides an API to implement measurement conversion.
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Convert a measurement unit. 2. Convert a measurement unit.
...@@ -393,7 +393,7 @@ The **I18NUtil** class provides an API to implement measurement conversion. ...@@ -393,7 +393,7 @@ The **I18NUtil** class provides an API to implement measurement conversion.
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Instantiates an **IndexUtil** object. 2. Instantiates an **IndexUtil** object.
...@@ -418,7 +418,7 @@ The **I18NUtil** class provides an API to implement measurement conversion. ...@@ -418,7 +418,7 @@ The **I18NUtil** class provides an API to implement measurement conversion.
Call **addLocale** to add the alphabet index of a new locale to the current index list. Call **addLocale** to add the alphabet index of a new locale to the current index list.
```js ```js
indexUtil.addLocale("ar") indexUtil.addLocale("ar");
``` ```
5. Obtain the index of a string. 5. Obtain the index of a string.
...@@ -454,7 +454,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc ...@@ -454,7 +454,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Instantiate a **BreakIterator** object. 2. Instantiate a **BreakIterator** object.
...@@ -462,7 +462,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc ...@@ -462,7 +462,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc
Call **getLineInstance** to instantiate a **BreakIterator** object. Call **getLineInstance** to instantiate a **BreakIterator** object.
```js ```js
let locale = "en-US" let locale = "en-US";
let breakIterator = I18n.getLineInstance(locale); let breakIterator = I18n.getLineInstance(locale);
``` ```
...@@ -531,7 +531,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc ...@@ -531,7 +531,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Instantiate the **TimeZone** object, and obtain the time zone information. 2. Instantiate the **TimeZone** object, and obtain the time zone information.
...@@ -592,7 +592,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to ...@@ -592,7 +592,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Obtains the transliterator ID list. 2. Obtains the transliterator ID list.
...@@ -637,7 +637,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to ...@@ -637,7 +637,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Check the input character has a certain attribute. 2. Check the input character has a certain attribute.
...@@ -719,7 +719,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to ...@@ -719,7 +719,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Check the sequence of year, month, and day in a date. 2. Check the sequence of year, month, and day in a date.
......
...@@ -25,7 +25,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug ...@@ -25,7 +25,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
Importing an incorrect bundle can lead to unexpected API behavior. Importing an incorrect bundle can lead to unexpected API behavior.
```js ```js
import Intl from '@ohos.intl' import Intl from '@ohos.intl';
``` ```
2. Instantiates a **Locale** object. 2. Instantiates a **Locale** object.
...@@ -100,7 +100,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug ...@@ -100,7 +100,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
Importing an incorrect bundle can lead to unexpected API behavior. Importing an incorrect bundle can lead to unexpected API behavior.
```js ```js
import Intl from '@ohos.intl' import Intl from '@ohos.intl';
``` ```
2. Instantiate a **DateTimeFormat** object. 2. Instantiate a **DateTimeFormat** object.
...@@ -170,7 +170,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug ...@@ -170,7 +170,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
Importing an incorrect bundle can lead to unexpected API behavior. Importing an incorrect bundle can lead to unexpected API behavior.
```js ```js
import Intl from '@ohos.intl' import Intl from '@ohos.intl';
``` ```
2. Instantiate a **NumberFormat** object. 2. Instantiate a **NumberFormat** object.
...@@ -195,7 +195,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug ...@@ -195,7 +195,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
```js ```js
let options = {compactDisplay: "short", notation: "compact"}; let options = {compactDisplay: "short", notation: "compact"};
let numberFormat = new Intl.NumberFormat("zh-CN", options); let numberFormat = new Intl.NumberFormat("zh-CN", options);
let number = 1234.5678 let number = 1234.5678;
let formatResult = numberFormat.format(number); // formatResult = "1235" let formatResult = numberFormat.format(number); // formatResult = "1235"
``` ```
...@@ -229,7 +229,7 @@ Users in different regions have different requirements for string sorting. [Coll ...@@ -229,7 +229,7 @@ Users in different regions have different requirements for string sorting. [Coll
Importing an incorrect bundle can lead to unexpected API behavior. Importing an incorrect bundle can lead to unexpected API behavior.
```js ```js
import Intl from '@ohos.intl' import Intl from '@ohos.intl';
``` ```
2. Instantiate a **Collator** object. 2. Instantiate a **Collator** object.
...@@ -240,7 +240,7 @@ Users in different regions have different requirements for string sorting. [Coll ...@@ -240,7 +240,7 @@ Users in different regions have different requirements for string sorting. [Coll
let collator = new Intl.Collator(); let collator = new Intl.Collator();
``` ```
Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions8). Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions9).
The **sensitivity** parameter is used to specify the levels of differences that will be used for string comparison. The value **base** indicates that only characters are compared, but not the accent and capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **accent** indicates that the accent is considered, but not the capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **case** indicates that the capitalization is considered, but the accent. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **variant** indicates that the accent and capitalization are considered. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The **sensitivity** parameter is used to specify the levels of differences that will be used for string comparison. The value **base** indicates that only characters are compared, but not the accent and capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **accent** indicates that the accent is considered, but not the capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **case** indicates that the capitalization is considered, but the accent. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **variant** indicates that the accent and capitalization are considered. For example, 'a' != 'b', 'a' == '', 'a'=='A'.
```js ```js
...@@ -290,7 +290,7 @@ According to grammars in certain languages, the singular or plural form of a nou ...@@ -290,7 +290,7 @@ According to grammars in certain languages, the singular or plural form of a nou
Importing an incorrect bundle can lead to unexpected API behavior. Importing an incorrect bundle can lead to unexpected API behavior.
```js ```js
import Intl from '@ohos.intl' import Intl from '@ohos.intl';
``` ```
2. Instantiate a **PluralRules** object. 2. Instantiate a **PluralRules** object.
...@@ -301,7 +301,7 @@ According to grammars in certain languages, the singular or plural form of a nou ...@@ -301,7 +301,7 @@ According to grammars in certain languages, the singular or plural form of a nou
let pluralRules = new Intl.PluralRules(); let pluralRules = new Intl.PluralRules();
``` ```
Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions8). Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions9).
```js ```js
let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"});
...@@ -313,7 +313,7 @@ According to grammars in certain languages, the singular or plural form of a nou ...@@ -313,7 +313,7 @@ According to grammars in certain languages, the singular or plural form of a nou
```js ```js
let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"});
let number = 1234.5678 let number = 1234.5678;
let categoryResult = pluralRules.select(number); // categoryResult = "other" let categoryResult = pluralRules.select(number); // categoryResult = "other"
``` ```
...@@ -338,7 +338,7 @@ According to grammars in certain languages, the singular or plural form of a nou ...@@ -338,7 +338,7 @@ According to grammars in certain languages, the singular or plural form of a nou
Importing an incorrect bundle can lead to unexpected API behavior. Importing an incorrect bundle can lead to unexpected API behavior.
```js ```js
import Intl from '@ohos.intl' import Intl from '@ohos.intl';
``` ```
2. Instantiate a **RelativeTimeFormat** object. 2. Instantiate a **RelativeTimeFormat** object.
...@@ -349,7 +349,7 @@ According to grammars in certain languages, the singular or plural form of a nou ...@@ -349,7 +349,7 @@ According to grammars in certain languages, the singular or plural form of a nou
let relativeTimeFormat = new Intl.RelativeTimeFormat(); let relativeTimeFormat = new Intl.RelativeTimeFormat();
``` ```
Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions8). Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions9).
```js ```js
let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
...@@ -362,7 +362,7 @@ According to grammars in certain languages, the singular or plural form of a nou ...@@ -362,7 +362,7 @@ According to grammars in certain languages, the singular or plural form of a nou
```js ```js
let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
let number = 2; let number = 2;
let unit = "year" let unit = "year";
let formatResult = relativeTimeFormat.format(number, unit); // 2 years later let formatResult = relativeTimeFormat.format(number, unit); // 2 years later
``` ```
...@@ -373,7 +373,7 @@ According to grammars in certain languages, the singular or plural form of a nou ...@@ -373,7 +373,7 @@ According to grammars in certain languages, the singular or plural form of a nou
```js ```js
let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
let number = 2; let number = 2;
let unit = "year" let unit = "year";
let formatPartsResult = relativeTimeFormat.formatToParts(number, unit); // formatPartsResult = [{"type": "integer", "value": "2", "unit": "year"}, {"type":"literal", "value": "years later"}] let formatPartsResult = relativeTimeFormat.formatToParts(number, unit); // formatPartsResult = [{"type": "integer", "value": "2", "unit": "year"}, {"type":"literal", "value": "years later"}]
``` ```
...@@ -390,6 +390,4 @@ According to grammars in certain languages, the singular or plural form of a nou ...@@ -390,6 +390,4 @@ According to grammars in certain languages, the singular or plural form of a nou
The following sample is provided to help you better understand how to develop internationalization capabilities: The following sample is provided to help you better understand how to develop internationalization capabilities:
-[`International`: Internationalization (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/International) -[`International`: Internationalization (ArkTS) (API9) (Full SDK)] (https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/Internationalnation/International)
-[`International`: Internationalization (ArkTS) (API8) (Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/International)
...@@ -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](audio-playback.md) - [Audio Playback Development (To Be Deprecated Soon)](audio-playback.md)
- [Audio Recording Development](audio-recorder.md) - [Audio Recording Development (To Be Deprecated Soon)](audio-recorder.md)
- [Video Playback Development](video-playback.md) - [Video Playback Development (To Be Deprecated Soon)](video-playback.md)
- [Video Recording Development](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)
......
...@@ -27,32 +27,43 @@ Before developing the audio data collection feature, configure the **ohos.permis ...@@ -27,32 +27,43 @@ Before developing the audio data collection feature, configure the **ohos.permis
For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md#audiocapturer8). For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md#audiocapturer8).
1. Use **createAudioCapturer()** to create an **AudioCapturer** instance. 1. Use **createAudioCapturer()** to create a global **AudioCapturer** instance.
Set parameters of the **AudioCapturer** instance in **audioCapturerOptions**. This instance is used to capture audio, control and obtain the recording state, and register a callback for notification. Set parameters of the **AudioCapturer** instance in **audioCapturerOptions**. This instance is used to capture audio, control and obtain the recording state, and register a callback for notification.
```js ```js
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
import fs from '@ohos.file.fs'; // It will be used for the call of the read function in step 3.
// Perform a self-test on APIs related to audio rendering.
@Entry
@Component
struct AudioRenderer {
@State message: string = 'Hello World'
private audioCapturer: audio.AudioCapturer; // It will be called globally.
async initAudioCapturer(){
let audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
let audioCapturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags: 0 // 0 is the extended flag bit of the audio capturer. The default value is 0.
}
let audioCapturerOptions = {
streamInfo: audioStreamInfo,
capturerInfo: audioCapturerInfo
}
this.audioCapturer = await audio.createAudioCapturer(audioCapturerOptions);
console.log('AudioRecLog: Create audio capturer success.');
}
let audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
let audioCapturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags: 0 // 0 is the extended flag bit of the audio capturer. The default value is 0.
}
let audioCapturerOptions = {
streamInfo: audioStreamInfo,
capturerInfo: audioCapturerInfo
}
let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions);
console.log('AudioRecLog: Create audio capturer success.');
``` ```
2. Use **start()** to start audio recording. 2. Use **start()** to start audio recording.
...@@ -60,23 +71,18 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference ...@@ -60,23 +71,18 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
The capturer state will be **STATE_RUNNING** once the audio capturer is started. The application can then begin reading buffers. The capturer state will be **STATE_RUNNING** once the audio capturer is started. The application can then begin reading buffers.
```js ```js
import audio from '@ohos.multimedia.audio'; async startCapturer() {
let state = this.audioCapturer.state;
async function startCapturer() {
let state = audioCapturer.state;
// The audio capturer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state after being started. // The audio capturer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state after being started.
if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || if (state == audio.AudioState.STATE_PREPARED || state == audio.AudioState.STATE_PAUSED ||
state != audio.AudioState.STATE_STOPPED) { state == audio.AudioState.STATE_STOPPED) {
console.info('Capturer is not in a correct state to start'); await this.audioCapturer.start();
return; state = this.audioCapturer.state;
} if (state == audio.AudioState.STATE_RUNNING) {
await audioCapturer.start(); console.info('AudioRecLog: Capturer started');
} else {
state = audioCapturer.state; console.error('AudioRecLog: Capturer start failed');
if (state == audio.AudioState.STATE_RUNNING) { }
console.info('AudioRecLog: Capturer started');
} else {
console.error('AudioRecLog: Capturer start failed');
} }
} }
``` ```
...@@ -86,91 +92,88 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference ...@@ -86,91 +92,88 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
The following example shows how to write recorded data into a file. The following example shows how to write recorded data into a file.
```js ```js
import fs from '@ohos.file.fs'; async readData(){
let state = this.audioCapturer.state;
let state = audioCapturer.state; // The read operation can be performed only when the state is STATE_RUNNING.
// The read operation can be performed only when the state is STATE_RUNNING. if (state != audio.AudioState.STATE_RUNNING) {
if (state != audio.AudioState.STATE_RUNNING) { console.info('Capturer is not in a correct state to read');
console.info('Capturer is not in a correct state to read'); return;
return;
}
const path = '/data/data/.pulse_dir/capture_js.wav'; // Path for storing the collected audio file.
let file = fs.openSync(filePath, 0o2);
let fd = file.fd;
if (file !== null) {
console.info('AudioRecLog: file created');
} else {
console.info('AudioRecLog: file create : FAILED');
return;
}
if (fd !== null) {
console.info('AudioRecLog: file fd opened in append mode');
}
let numBuffersToCapture = 150; // Write data for 150 times.
let count = 0;
while (numBuffersToCapture) {
let bufferSize = await audioCapturer.getBufferSize();
let buffer = await audioCapturer.read(bufferSize, true);
let options = {
offset: count * this.bufferSize,
length: this.bufferSize
} }
if (typeof(buffer) == undefined) { const path = '/data/data/.pulse_dir/capture_js.wav'; // Path for storing the collected audio file.
console.info('AudioRecLog: read buffer failed'); let file = fs.openSync(path, 0o2);
let fd = file.fd;
if (file !== null) {
console.info('AudioRecLog: file created');
} else { } else {
let number = fs.writeSync(fd, buffer, options); console.info('AudioRecLog: file create : FAILED');
console.info(`AudioRecLog: data written: ${number}`); return;
} }
numBuffersToCapture--; if (fd !== null) {
count++; console.info('AudioRecLog: file fd opened in append mode');
}
let numBuffersToCapture = 150; // Write data for 150 times.
let count = 0;
while (numBuffersToCapture) {
this.bufferSize = await this.audioCapturer.getBufferSize();
let buffer = await this.audioCapturer.read(this.bufferSize, true);
let options = {
offset: count * this.bufferSize,
length: this.bufferSize
}
if (typeof(buffer) == undefined) {
console.info('AudioRecLog: read buffer failed');
} else {
let number = fs.writeSync(fd, buffer, options);
console.info(`AudioRecLog: data written: ${number}`);
}
numBuffersToCapture--;
count++;
}
} }
``` ```
4. Once the recording is complete, call **stop()** to stop the recording. 4. Once the recording is complete, call **stop()** to stop the recording.
```js ```js
async function StopCapturer() { async StopCapturer() {
let state = audioCapturer.state; let state = this.audioCapturer.state;
// The audio capturer can be stopped only when it is in STATE_RUNNING or STATE_PAUSED state. // The audio capturer can be stopped only when it is in STATE_RUNNING or STATE_PAUSED state.
if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) { if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) {
console.info('AudioRecLog: Capturer is not running or paused'); console.info('AudioRecLog: Capturer is not running or paused');
return; return;
} }
await audioCapturer.stop(); await this.audioCapturer.stop();
state = audioCapturer.state; state = this.audioCapturer.state;
if (state == audio.AudioState.STATE_STOPPED) { if (state == audio.AudioState.STATE_STOPPED) {
console.info('AudioRecLog: Capturer stopped'); console.info('AudioRecLog: Capturer stopped');
} else { } else {
console.error('AudioRecLog: Capturer stop failed'); console.error('AudioRecLog: Capturer stop failed');
} }
} }
``` ```
5. After the task is complete, call **release()** to release related resources. 5. After the task is complete, call **release()** to release related resources.
```js ```js
async function releaseCapturer() { async releaseCapturer() {
let state = audioCapturer.state; let state = this.audioCapturer.state;
// The audio capturer can be released only when it is not in the STATE_RELEASED or STATE_NEW state. // The audio capturer can be released only when it is not in the STATE_RELEASED or STATE_NEW state.
if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) {
console.info('AudioRecLog: Capturer already released'); console.info('AudioRecLog: Capturer already released');
return; return;
} }
await audioCapturer.release(); await this.audioCapturer.release();
state = audioCapturer.state; state = this.audioCapturer.state;
if (state == audio.AudioState.STATE_RELEASED) { if (state == audio.AudioState.STATE_RELEASED) {
console.info('AudioRecLog: Capturer released'); console.info('AudioRecLog: Capturer released');
} else { } else {
console.info('AudioRecLog: Capturer release failed'); console.info('AudioRecLog: Capturer release failed');
} }
} }
``` ```
6. (Optional) Obtain the audio capturer information. 6. (Optional) Obtain the audio capturer information.
...@@ -178,23 +181,20 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference ...@@ -178,23 +181,20 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
You can use the following code to obtain the audio capturer information: You can use the following code to obtain the audio capturer information:
```js ```js
// Obtain the audio capturer state. async getAudioCapturerInfo(){
let state = audioCapturer.state; // Obtain the audio capturer state.
let state = this.audioCapturer.state;
// Obtain the audio capturer information. // Obtain the audio capturer information.
let audioCapturerInfo : audio.AuduioCapturerInfo = await audioCapturer.getCapturerInfo(); let audioCapturerInfo : audio.AudioCapturerInfo = await this.audioCapturer.getCapturerInfo();
// Obtain the audio stream information.
// Obtain the audio stream information. let audioStreamInfo : audio.AudioStreamInfo = await this.audioCapturer.getStreamInfo();
let audioStreamInfo : audio.AudioStreamInfo = await audioCapturer.getStreamInfo(); // Obtain the audio stream ID.
let audioStreamId : number = await this.audioCapturer.getAudioStreamId();
// Obtain the audio stream ID. // Obtain the Unix timestamp, in nanoseconds.
let audioStreamId : number = await audioCapturer.getAudioStreamId(); let audioTime : number = await this.audioCapturer.getAudioTime();
// Obtain a proper minimum buffer size.
// Obtain the Unix timestamp, in nanoseconds. let bufferSize : number = await this.audioCapturer.getBufferSize();
let audioTime : number = await audioCapturer.getAudioTime(); }
// Obtain a proper minimum buffer size.
let bufferSize : number = await audioCapturer.getBufferSize();
``` ```
7. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event. 7. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event.
...@@ -202,12 +202,13 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference ...@@ -202,12 +202,13 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
After the mark reached event is subscribed to, when the number of frames collected by the audio capturer reaches the specified value, a callback is triggered and the specified value is returned. After the mark reached event is subscribed to, when the number of frames collected by the audio capturer reaches the specified value, a callback is triggered and the specified value is returned.
```js ```js
audioCapturer.on('markReach', (reachNumber) => { async markReach(){
console.info('Mark reach event Received'); this.audioCapturer.on('markReach', 10, (reachNumber) => {
console.info(`The Capturer reached frame: ${reachNumber}`); console.info('Mark reach event Received');
}); console.info(`The Capturer reached frame: ${reachNumber}`);
});
audioCapturer.off('markReach'); // Unsubscribe from the mark reached event. This event will no longer be listened for. this.audioCapturer.off('markReach'); // Unsubscribe from the mark reached event. This event will no longer be listened for.
}
``` ```
8. (Optional) Use **on('periodReach')** to subscribe to the period reached event, and use **off('periodReach')** to unsubscribe from the event. 8. (Optional) Use **on('periodReach')** to subscribe to the period reached event, and use **off('periodReach')** to unsubscribe from the event.
...@@ -215,40 +216,43 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference ...@@ -215,40 +216,43 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
After the period reached event is subscribed to, each time the number of frames collected by the audio capturer reaches the specified value, a callback is triggered and the specified value is returned. After the period reached event is subscribed to, each time the number of frames collected by the audio capturer reaches the specified value, a callback is triggered and the specified value is returned.
```js ```js
audioCapturer.on('periodReach', (reachNumber) => { async periodReach(){
console.info('Period reach event Received'); this.audioCapturer.on('periodReach', 10, (reachNumber) => {
console.info(`In this period, the Capturer reached frame: ${reachNumber}`); console.info('Period reach event Received');
}); console.info(`In this period, the Capturer reached frame: ${reachNumber}`);
});
audioCapturer.off('periodReach'); // Unsubscribe from the period reached event. This event will no longer be listened for. this.audioCapturer.off('periodReach'); // Unsubscribe from the period reached event. This event will no longer be listened for.
}
``` ```
9. If your application needs to perform some operations when the audio capturer state is updated, it can subscribe to the state change event. When the audio capturer state is updated, the application receives a callback containing the event type. 9. If your application needs to perform some operations when the audio capturer state is updated, it can subscribe to the state change event. When the audio capturer state is updated, the application receives a callback containing the event type.
```js ```js
audioCapturer.on('stateChange', (state) => { async stateChange(){
console.info(`AudioCapturerLog: Changed State to : ${state}`) this.audioCapturer.on('stateChange', (state) => {
switch (state) { console.info(`AudioCapturerLog: Changed State to : ${state}`)
case audio.AudioState.STATE_PREPARED: switch (state) {
console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); case audio.AudioState.STATE_PREPARED:
console.info('Audio State is : Prepared'); console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------');
break; console.info('Audio State is : Prepared');
case audio.AudioState.STATE_RUNNING: break;
console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); case audio.AudioState.STATE_RUNNING:
console.info('Audio State is : Running'); console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------');
break; console.info('Audio State is : Running');
case audio.AudioState.STATE_STOPPED: break;
console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); case audio.AudioState.STATE_STOPPED:
console.info('Audio State is : stopped'); console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------');
break; console.info('Audio State is : stopped');
case audio.AudioState.STATE_RELEASED: break;
console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); case audio.AudioState.STATE_RELEASED:
console.info('Audio State is : released'); console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------');
break; console.info('Audio State is : released');
default: break;
console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); default:
console.info('Audio State is : invalid'); console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------');
break; console.info('Audio State is : invalid');
} break;
}); }
});
}
``` ```
...@@ -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
} }
} }
``` ```
......
# 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.
......
...@@ -27,7 +27,7 @@ In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#n ...@@ -27,7 +27,7 @@ In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#n
```ts ```ts
notificationManager.isSupportTemplate('downloadTemplate').then((data) => { notificationManager.isSupportTemplate('downloadTemplate').then((data) => {
console.info(`[ANS] isSupportTemplate success`); console.info(`[ANS] isSupportTemplate success`);
let isSupportTpl: boolean = data; // The value **true** means that the template of the **downloadTemplate** type is supported; and false means the opposite. let isSupportTpl: boolean = data; // The value true means that the template of the downloadTemplate type is supported, and false means the opposite.
// ... // ...
}).catch((err) => { }).catch((err) => {
console.error(`[ANS] isSupportTemplate failed, code is ${err.code}, message is ${err.message}`); console.error(`[ANS] isSupportTemplate failed, code is ${err.code}, message is ${err.message}`);
......
...@@ -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
} }
} }
} }
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,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)
......
# 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.
...@@ -42,6 +42,8 @@ ForEach( ...@@ -42,6 +42,8 @@ ForEach(
) )
``` ```
Since API version 9, this API is supported in ArkTS widgets.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
......
# Full SDK Compilation Guide
The full SDK provides a full set of APIs available in OpenHarmony, including system APIs required by system applications. Vendors can leverage this SDK to develop applications.
Since OpenHarmony 3.2 Beta5, the full SDK is not provided with the version. If necessary, you can compile the SDK using the full source code.
## Compiling the Full SDK
**Preparation**
1. Register an SSH public key for access to Gitee.
2. Configure the server environment. For details, see [Setting Up the Ubuntu Environment](../../device-dev/quick-start/quickstart-ide-env-ubuntu.md).
**Procedure**
1. Download and initialize the manifest repository: **repo init -u https://gitee.com/openharmony/manifest.git -b $manifest_branch --no-repo-verify --repo-url=https://gitee.com/oschina/repo --no-clone-bundle**
2. Download source code based on the downloaded manifest repository: **repo sync -c -d --force-sync**
3. Perform precompilation: **yes y | apt install libxinerama-dev libxcursor-dev libxrandr-dev libxi-dev && rm -rf prebuilts/clang/ohos/darwin-x86_64/clang-480513 && rm -rf prebuilts/clang/ohos/windows-x86_64/clang-480513 && rm -rf prebuilts/clang/ohos/linux-x86_64/clang-480513 && bash build/prebuilts_download.sh -ndk && apt-get update -qqy && apt-get install doxygen -y --force-yes**
4. Perform compilation: **./build.sh --product-name ohos-sdk**
If the compilation is successful, export the files in the **out/sdk/packages/ohos-sdk/** directory.
## Replacing the SDK
After the full SDK is compiled, switch to it in DevEco Studio. For details, see [Guide to Switching to Full SDK](../../application-dev/quick-start/full-sdk-switch-guide.md).
# 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).
此差异已折叠。
此差异已折叠。
...@@ -35,7 +35,7 @@ resources ...@@ -35,7 +35,7 @@ resources
| Category | base Subdirectory | Qualifiers Subdirectory | rawfile Subdirectory | | Category | base Subdirectory | Qualifiers Subdirectory | rawfile Subdirectory |
| ---- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | | ---- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| Structure| The **base** subdirectory is a default directory. If no qualifiers subdirectories in the **resources** directory of the application match the device status, the resource file in the **base** subdirectory will be automatically referenced.<br>Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories).| You need to create qualifiers subdirectories on your own. Each directory name consists of one or more qualifiers that represent the application scenarios or device characteristics. For details, see [Qualifiers Subdirectories](#qualifiers-subdirectories).<br>Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories). | You can create multiple levels of subdirectories with custom directory names. They can be used to store various resource files.<br>However, resource files in the **rawfile** subdirectory will not be matched based on the device status.| | Structure| The **base** subdirectory is a default directory. If no qualifiers subdirectories in the **resources** directory of the application match the device status, the resource file in the **base** subdirectory will be automatically referenced.<br>Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories).| You need to create qualifiers subdirectories on your own. Each directory name consists of one or more qualifiers that represent the application scenarios or device characteristics. For details, see [Qualifiers Subdirectories](#qualifiers-subdirectories).<br>Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories).| You can create multiple levels of subdirectories with custom directory names. They can be used to store various resource files.<br>However, resource files in the **rawfile** subdirectory will not be matched based on the device status.|
| Compilation| Resource files in the subdirectory are compiled into binary files, and each resource file is assigned an ID. | Resource files in the subdirectory are compiled into binary files, and each resource file is assigned an ID. | Resource files in the subdirectory are directly packed into the application without being compiled, and no IDs will be assigned to the resource files. | | Compilation| Resource files in the subdirectory are compiled into binary files, and each resource file is assigned an ID. | Resource files in the subdirectory are compiled into binary files, and each resource file is assigned an ID. | Resource files in the subdirectory are directly packed into the application without being compiled, and no IDs will be assigned to the resource files. |
| Reference| Resource files in the subdirectory are referenced based on the resource type and resource name. | Resource files in the subdirectory are referenced based on the resource type and resource name. | Resource files in the subdirectory are referenced based on the file path and file name. | | Reference| Resource files in the subdirectory are referenced based on the resource type and resource name. | Resource files in the subdirectory are referenced based on the resource type and resource name. | Resource files in the subdirectory are referenced based on the file path and file name. |
...@@ -81,9 +81,9 @@ You can create resource group subdirectories (including element, media, and prof ...@@ -81,9 +81,9 @@ You can create resource group subdirectories (including element, media, and prof
| Resource Group Subdirectory | Description | Resource File | | Resource Group Subdirectory | Description | Resource File |
| ------- | ---------------------------------------- | ---------------------------------------- | | ------- | ---------------------------------------- | ---------------------------------------- |
| element | Indicates element resources. Each type of data is represented by a JSON file. The options are as follows:<br>- **boolean**: boolean data<br>- **color**: color data<br>- **float**: floating-point data<br>- **intarray**: array of integers<br>- **integer**: integer data<br>- **pattern**: pattern data<br>- **plural**: plural form data<br>- **strarray**: array of strings<br>- **string**: string data| It is recommended that files in the **element** subdirectory be named the same as the following files, each of which can contain only data of the same type:<br>- boolean.json<br>- color.json<br>- float.json<br>- intarray.json<br>- integer.json<br>- pattern.json<br>- plural.json<br>- strarray.json<br>- string.json | | element | Indicates element resources. Each type of data is represented by a JSON file. (Only files are supported in this directory.) The options are as follows:<br>- **boolean**: boolean data<br>- **color**: color data<br>- **float**: floating-point data<br>- **intarray**: array of integers<br>- **integer**: integer data<br>- **pattern**: pattern data<br>- **plural**: plural form data<br>- **strarray**: array of strings<br>- **string**: string data| It is recommended that files in the **element** subdirectory be named the same as the following files, each of which can contain only data of the same type:<br>- boolean.json<br>- color.json<br>- float.json<br>- intarray.json<br>- integer.json<br>- pattern.json<br>- plural.json<br>- strarray.json<br>- string.json |
| media | Indicates media resources, including non-text files such as images, audios, and videos. | The file name can be customized, for example, **icon.png**. | | media | Indicates media resources, including non-text files such as images, audios, and videos. (Only files are supported in this directory.) | The file name can be customized, for example, **icon.png**. |
| profile | Indicates a user-defined configuration file. You can obtain the file content by using the [getProfileByAbility](../reference/apis/js-apis-bundleManager.md#bundlemanagergetprofilebyability) API. | The file name can be customized, for example, **test_profile.json**. | | profile | Indicates a custom configuration file. You can obtain the file content by using the [getProfileByAbility](../reference/apis/js-apis-bundleManager.md#bundlemanagergetprofilebyability) API. (Only files are supported in this directory.) | The file name can be customized, for example, **test_profile.json**. |
| rawfile | Indicates other types of files, which are stored in their raw formats after the application is built as an HAP file. They will not be integrated into the **resources.index** file.| The file name can be customized. | | rawfile | Indicates other types of files, which are stored in their raw formats after the application is built as an HAP file. They will not be integrated into the **resources.index** file.| The file name can be customized. |
**Media Resource Types** **Media Resource Types**
...@@ -229,7 +229,7 @@ When referencing resources in the **rawfile** subdirectory, use the **"$rawfile( ...@@ -229,7 +229,7 @@ When referencing resources in the **rawfile** subdirectory, use the **"$rawfile(
> >
> Resource descriptors accept only strings, such as **'app.type.name'**, and cannot be combined. > Resource descriptors accept only strings, such as **'app.type.name'**, and cannot be combined.
> >
> The return value of **$r** is a **Resource** object. You can obtain the corresponding string by using the [getStringValue](../reference/apis/js-apis-resource-manager.md) API. > The return value of **$r** is a **Resource** object. You can obtain the corresponding string by using the [getStringValue](../reference/apis/js-apis-resource-manager.md#getstringvalue9) API.
In the **.ets** file, you can use the resources defined in the **resources** directory. The following is a resource usage example based on the resource file examples in [Resource Group Sub-directories](#resource-group-subdirectories): In the **.ets** file, you can use the resources defined in the **resources** directory. The following is a resource usage example based on the resource file examples in [Resource Group Sub-directories](#resource-group-subdirectories):
...@@ -252,7 +252,6 @@ Text($r('app.string.message_arrive', "five'o clock")) ...@@ -252,7 +252,6 @@ Text($r('app.string.message_arrive', "five'o clock"))
Text($r('app.plural.eat_apple', 5, 5)) Text($r('app.plural.eat_apple', 5, 5))
.fontColor($r('app.color.color_world')) .fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_world')) .fontSize($r('app.float.font_world'))
}
Image($r('app.media.my_background_image')) // Reference media resources. Image($r('app.media.my_background_image')) // Reference media resources.
......
# 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.
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册