提交 3175b96d 编写于 作者: 田雨 提交者: Gitee

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

Signed-off-by: N田雨 <tianyu55@huawei.com>
......@@ -2,52 +2,87 @@
- [Application Development Overview](application-dev-guide.md)
- About OpenHarmony
- [OpenHarmony Project](../OpenHarmony-Overview.md)
- [Glossary](../glossary.md)
- [OpenHarmony Release Notes](../release-notes/Readme.md)
- [OpenHarmony Project](../OpenHarmony-Overview.md)
- [Glossary](../glossary.md)
- [OpenHarmony Release Notes](../release-notes/Readme.md)
- Quick Start
- Getting Started
- [Preparations](quick-start/start-overview.md)
- [Getting Started with ArkTS in Stage Model](quick-start/start-with-ets-stage.md)
- [Getting Started with ArkTS in FA Model](quick-start/start-with-ets-fa.md)
- [Getting Started with JavaScript in FA Model](quick-start/start-with-js-fa.md)
- Development Fundamentals
- [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md)
- [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md)
- [SysCap](quick-start/syscap.md)
- Getting Started
- [Before You Start](quick-start/start-overview.md)
- [Getting Started with ArkTS in Stage Model](quick-start/start-with-ets-stage.md)
- [Getting Started with ArkTS in FA Model](quick-start/start-with-ets-fa.md)
- [Getting Started with JavaScript in FA Model](quick-start/start-with-js-fa.md)
- Development Fundamentals
- Application Package Fundamentals
- [Application Package Overview](quick-start/application-package-overview.md)
- Application Package Structure
- [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)
- [HAR File Structure](quick-start/har-structure.md)
- Multi-HAP Mechanism
- [Multi-HAP Design Objectives](quick-start/multi-hap-objective.md)
- [Multi-HAP Build View](quick-start/multi-hap-build-view.md)
- [Multi-HAP Development, Debugging, Release, and Deployment Process](quick-start/multi-hap-release-deployment.md)
- [Multi-HAP Usage Rules](quick-start/multi-hap-rules.md)
- [Multi-HAP Operation Mechanism and Data Communication Modes](quick-start/multi-hap-principles.md)
- [Application Installation and Uninstallation Process](quick-start/application-package-install-uninstall.md)
- Application Configuration Files in Stage Model
- [Application Configuration File Overview (Stage Model)](quick-start/application-configuration-file-overview-stage.md)
- [app.json5 Configuration File](quick-start/app-configuration-file.md)
- [module.json5 Configuration File](quick-start/module-configuration-file.md)
- Application Configuration Files in FA Model
- [Application Configuration File Overview (FA Model)](quick-start/application-configuration-file-overview-fa.md)
- [Internal Structure of the app Tag](quick-start/app-structure.md)
- [Internal structure of deviceConfig Tag](quick-start/deviceconfig-structure.md)
- [Internal Structure of the module Tag](quick-start/module-structure.md)
- [Resource Categories and Access](quick-start/resource-categories-and-access.md)
- Learning ArkTS
- [Getting Started with ArkTS](quick-start/arkts-get-started.md)
- ArkTS Syntax (Declarative UI)
- [Basic UI Description](quick-start/arkts-basic-ui-description.md)
- State Management
- [Basic Concepts](quick-start/arkts-state-mgmt-concepts.md)
- [State Management with Page-level Variables](quick-start/arkts-state-mgmt-page-level.md)
- [State Management with Application-level Variables](quick-start/arkts-state-mgmt-application-level.md)
- [Dynamic UI Element Building](quick-start/arkts-dynamic-ui-elememt-building.md)
- [Rendering Control](quick-start/arkts-rendering-control.md)
- [Restrictions and Extensions](quick-start/arkts-restrictions-and-extensions.md)
- Development
- [Ability Development](ability/Readme-EN.md)
- [UI Development](ui/Readme-EN.md)
- [Common Event and Notification](notification/Readme-EN.md)
- [Window Manager](windowmanager/Readme-EN.md)
- [WebGL](webgl/Readme-EN.md)
- [Media](media/Readme-EN.md)
- [Security](security/Readme-EN.md)
- [Connectivity](connectivity/Readme-EN.md)
- [Data Management](database/Readme-EN.md)
- [File Management](file-management/Readme-EN.md)
- [Telephony](telephony/Readme-EN.md)
- [Task Management](task-management/Readme-EN.md)
- [Device Management](device/Readme-EN.md)
- [Device Usage Statistics](device-usage-statistics/Readme-EN.md)
- [DFX](dfx/Readme-EN.md)
- [Internationalization](internationalization/Readme-EN.md)
- [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md)
- [Using Native APIs in Application Projects](napi/Readme-EN.md)
- [Application Models](application-models/Readme-EN.md)
- [UI Development](ui/Readme-EN.md)
- [Common Event and Notification](notification/Readme-EN.md)
- [Window Manager](windowmanager/Readme-EN.md)
- [WebGL](webgl/Readme-EN.md)
- [Media](media/Readme-EN.md)
- [Security](security/Readme-EN.md)
- [Connectivity](connectivity/Readme-EN.md)
- [Data Management](database/Readme-EN.md)
- [File Management](file-management/Readme-EN.md)
- [Telephony](telephony/Readme-EN.md)
- [Task Management](task-management/Readme-EN.md)
- [Device Management](device/Readme-EN.md)
- [Device Usage Statistics](device-usage-statistics/Readme-EN.md)
- [DFX](dfx/Readme-EN.md)
- [Internationalization](internationalization/Readme-EN.md)
- [Application Test](application-test/Readme-EN.md)
- [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md)
- [Using Native APIs in Application Projects](napi/Readme-EN.md)
- Tools
- [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md)
- Hands-On Tutorials
- [Samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md)
- [Codelabs](https://gitee.com/openharmony/codelabs)
- API References
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- APIs
- [JS and TS APIs](reference/apis/Readme-EN.md)
- Native APIs
- [Standard Libraries](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md)
- [SystemCapability](reference/syscap.md)
- [SystemCapability List](reference/syscap-list.md)
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- [JS Service Widget UI Components](reference/js-service-widget-ui/Readme-EN.md)
- APIs
- [ArkTS and JS APIs](reference/apis/Readme-EN.md)
- [Error Codes](reference/errorcodes/Readme-EN.md)
- Native APIs
- [Standard Libraries](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md)
- [FAQs](faqs/Readme-EN.md)
- Contribution
- [How to Contribute](../contribute/documentation-contribution.md)
- [How to Contribute](../contribute/documentation-contribution.md)
......@@ -18,7 +18,7 @@ To facilitate your application development, we provide development guidelines fo
First thing first, familiarize yourself with the two cornerstone frameworks in OpenHarmony applications:
- Application framework: [Ability Development](ability/Readme-EN.md)
- Application framework: [Application Models](application-models/Readme-EN.md)
- UI framework: [UI Development](ui/Readme-EN.md)
All applications should be developed on top of these frameworks.
......@@ -37,6 +37,7 @@ Then, equip yourself for developing the key features, with the following guideli
- [Device Usage Statistics](device-usage-statistics/Readme-EN.md)
- [DFX](dfx/Readme-EN.md)
- [Internationalization](internationalization/Readme-EN.md)
- [Application Test](application-test/Readme-EN.md)
- [IDL Specifications and User Guide](IDL/idl-guidelines.md)
- [Using Native APIs in Application Projects](napi/Readme-EN.md)
......@@ -56,11 +57,11 @@ API references encompass all components and APIs available in OpenHarmony, helpi
They are organized as follows:
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- APIs
- [JS and TS APIs](reference/apis/Readme-EN.md)
- Native APIs
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- [JS Service Widget UI Components](reference/js-service-widget-ui/Readme-EN.md)
- APIs
- [JS and TS APIs](reference/apis/Readme-EN.md)
- Native APIs
- [Standard Library](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md)
......
......@@ -18,7 +18,7 @@ To facilitate your application development, we provide development guidelines fo
First thing first, familiarize yourself with the two cornerstone frameworks in OpenHarmony applications:
- Application framework: [Ability Development](ability/fa-brief.md)
- Application framework: [Application Models](application-models/application-model-composition.md)
- UI framework: [UI Development](ui/arkui-overview.md)
All applications should be developed on top of these frameworks.
......@@ -35,8 +35,9 @@ Then, equip yourself for developing the key features, with the following guideli
- [Task Management](task-management/background-task-overview.md)
- [Device](device/usb-overview.md)
- [Device Usage Statistics](device-usage-statistics/device-usage-statistics-overview.md)
- [DFX](dfx/hiappevent-overview.md)
- [DFX](dfx/hiappevent-guidelines.md)
- [Internationalization](internationalization/international-overview.md)
- [Application Test](application-test/arkxtest-guidelines.md)
- [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md)
- [Using Native APIs in Application Projects](napi/napi-guidelines.md)
......@@ -59,7 +60,9 @@ They are organized as follows:
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- [JS and TS APIs](reference/apis/js-apis-DataUriUtils.md)
- [JS Service Widget UI Components](reference/js-service-widget-ui/Readme-EN.md)
- [JS and TS APIs](reference/apis/js-apis-ability-dataUriUtils.md)
- Native APIs
- [Standard Library](reference/native-lib/third_party_libc/musl.md)
......
......@@ -78,6 +78,5 @@ The **module.json5** of a browser application is as follows:
4. If **type** in the passed **want** parameter is specified and is included in **type** under **skills**, the matching is successful.
2. When there are multiple matching applications, a dialog box is displayed for you to select one of them.
<img src="figures/stage-want1.png" alt="stage-want1" style="zoom:80%;" />
\ No newline at end of file
2. When there are multiple matching applications, a dialog box is displayed for you to select one of them.
<img src="figures/stage-want1.png" alt="stage-want1" style="zoom:80%;" />
......@@ -55,4 +55,3 @@ When an application is switched to the background, it is cached in the backgroun
}
```
<!--no_check-->
\ No newline at end of file
......@@ -2,6 +2,7 @@
The [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) field specifies the common operation (such as viewing, sharing, and application details) to be performed by the caller. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data, for example, viewing URI data. For example, if the URI is a website and the action is **ohos.want.action.viewData**, the ability that supports website viewing is matched. Declaring the **action** field in Want indicates that the invoked application should support the declared operation. The **actions** field under **skills** in the configuration file indicates the operations supported by the application.
**Common action Values**
......@@ -15,6 +16,7 @@ The [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantactio
The [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) field specifies the additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want. You can define this field to filter application categories, for example, browser. Declaring the **entities** field in Want indicates that the invoked application should belong to the declared category. The **entities** field under **skills** in the configuration file indicates the categories supported by the application.
**Common entities Values**
......
......@@ -13,8 +13,8 @@ Due to the differences in the thread model and process model, certain APIs (mark
import fa from '@ohos.ability.featureAbility';
let parameter = {
"want": {
bundleName: "ohos.samples.demo",
abilityName: "ohos.samples.demo.MainAbility"
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.EntryAbility"
}
}
fa.startAbility(parameter).then((data) => {
......@@ -30,8 +30,8 @@ Due to the differences in the thread model and process model, certain APIs (mark
// context is a member of the ability object and is required for invoking inside a non-ability object.
// Pass in the Context object.
let wantInfo = {
bundleName: "ohos.samples.demo",
abilityName: "ohos.samples.demo.MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
this.context.startAbility(wantInfo).then((data) => {
console.info('startAbility success.');
......
......@@ -28,4 +28,3 @@ OpenHarmony has reconstructed the [deviceConfig](../quick-start/deviceconfig-str
| compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed.| / | This configuration is not supported in the stage model.|
| network | Network security configuration.| / | This configuration is not supported in the stage model.|
<!--no_check-->
\ No newline at end of file
......@@ -38,4 +38,3 @@ When developing an application, you may need to configure certain tags to identi
To request component permissions, set the **reqPermission** field under **module** in the **config.json** file. This field declares the name of the permission to request, the reason for requesting the permission, and the scenario where the permission is used. For details about the configuration, see [reqPermission](../quick-start/module-structure.md).
<!--no_check-->
\ No newline at end of file
......@@ -3,8 +3,7 @@
When developing an application, you may need to configure certain tags to identify the application, such as the bundle name and application icon. This topic describes key tags that need to be configured during application development. Icons and labels are usually configured together. There is the application icon, application label, entry icon, and entry label, which correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). The application icon and label are used in **Settings**. For example, they are displayed in the application list in **Settings**. The entry icon is displayed on the device's home screen after the application is installed. The entry icon maps to a [UIAbility](uiability-overview.md) component. Therefore, an application can have multiple entry icons and labels. When you touch one of them, the corresponding UIAbility page is displayed.
**Figure 1** Icons and labels
**Figure 1** Icons and labels
![application-component-configuration-stage](figures/application-component-configuration-stage.png)
......@@ -71,4 +70,3 @@ When developing an application, you may need to configure certain tags to identi
The **requestPermission** field in the [module.json5 file](../quick-start/module-configuration-file.md) is used to configure the permission information required by the module to access the protected part of the system or other applications. This field declares the name of the permission to request, the reason for requesting the permission, and the scenario where the permission is used.
<!--no_check-->
\ No newline at end of file
......@@ -12,7 +12,7 @@
<img src="figures/context-holding.png" alt="context-holding" style="zoom:50%;" />
- The following describes the information provided by different contexts.
- [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md): Each UIAbility has the **Context** attribute, which provides APIs to operate the ability, obtain the ability configuration, request permissions from users, and more.
- [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md): Each UIAbility has the **Context** attribute, which provides APIs to operate the ability, obtain the ability configuration, and more.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
......@@ -65,15 +65,10 @@ This topic describes how to use the context in the following scenarios:
- [Obtaining the Application Development Path](#obtaining-the-application-development-path)
- [Obtaining and Modifying Encrypted Areas](#obtaining-and-modifying-encrypted-areas)
- [Creating Context of Another Application or Module](#creating-context-of-another-application-or-module)
- [Subscribing to Ability Lifecycle Changes in a Process](#subscribing-to-ability-lifecycle-changes-in-a-process)
- [Requesting Permissions from Users Through AbilityContext](#requesting-permissions-from-users-through-uiabilitycontext)
### Obtaining the Application Development Path
......@@ -180,9 +175,9 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
> - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
>
> - This is a system API and cannot be called by third-party applications.
For example, application information displayed on the home screen includes the application name and icon. The home screen application calls the foregoing method to obtain the context information, so as to obtain the resource information including the application name and icon.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
......@@ -194,8 +189,8 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
// ...
}
}
```
```
- Call **createModuleContext(bundleName:string, moduleName:string)** to obtain the context of a specified module of another application. After obtaining the context, you can obtain the resource information of that module.
> **NOTE**
>
......@@ -204,7 +199,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
> - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
>
> - This is a system API and cannot be called by third-party applications.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
......@@ -217,7 +212,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
}
}
```
- Call **createModuleContext(moduleName:string)** to obtain the context of another module in the current application. After obtaining the context, you can obtain the resource information of that module.
```ts
......@@ -242,7 +237,7 @@ When the ability lifecycle changes in a process, for example, being created or d
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import Window from '@ohos.window';
import window from '@ohos.window';
const TAG: string = "[Example].[Entry].[EntryAbility]";
......@@ -298,14 +293,3 @@ export default class EntryAbility extends UIAbility {
}
}
```
### Requesting Permissions from Users Through UIAbilityContext
Each ability has the **Context** attribute. The ability is used to process the lifecycle. Methods use to operate the ability (such as **startAbility()**, **connectServiceExtensionAbility()**, and **terminateSelf()**) are implemented in the corresponding context. The context also provides methods for obtaining the ability configuration and requesting permissions from users. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
When an application needs to obtain users' privacy information or use system capabilities, for example, to obtain location information, to access the calendar, or to use the camera to take photos or record videos, the application must request permissions from users, as shown below. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md).
**Figure 2** Requesting the permission to access the calendar from users
<img src="figures/application-context-stage.png" alt="application-context-stage" style="zoom:50%;" />
\ No newline at end of file
......@@ -58,4 +58,3 @@ The table below describes their differences in detail.
| **Mission management model**| - A mission is created for each PageAbility component instance.<br>- Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions.<br>- PageAbility components do not form a stack structure.<br>For details, see [Mission Management Scenarios](mission-management-overview.md).| - A mission is created for each UIAbility component instance.<br>- Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions.<br>- UIAbility components do not form a stack structure.<br>For details, see [Mission Management Scenarios](mission-management-overview.md).|
| **Application configuration file**| The **config.json** file is used to describe the application, HAP, and application component information.<br>For details, see [Application Configuration File Overview (FA Model)](../quick-start/application-configuration-file-overview-fa.md).| The **app.json5** file is used to describe the application information, and the **module.json5** file is used to describe the HAP and application component information.<br>For details, see [Application Configuration File Overview (Stage Model)](../quick-start/application-configuration-file-overview-stage.md).|
<!--no_check-->
\ No newline at end of file
......@@ -12,15 +12,15 @@ A UIAbility accesses a ServiceAbility in the same way as it accesses a ServiceEx
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
export default class MainAbility extends UIAbility {
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
console.info("MainAbility onCreate");
console.info("EntryAbility onCreate");
}
onDestroy() {
console.info("MainAbility onDestroy")
console.info("EntryAbility onDestroy")
}
onWindowStageCreate(windowStage) {
console.info("MainAbility onWindowStageCreate")
console.info("EntryAbility onWindowStageCreate")
let want = {
bundleName: "com.ohos.fa",
abilityName: "ServiceAbility",
......@@ -40,13 +40,13 @@ export default class MainAbility extends UIAbility {
let connectionId = this.context.connectServiceExtensionAbility(want, options);
}
onWindowStageDestroy() {
console.info("MainAbility onWindowStageDestroy")
console.info("EntryAbility onWindowStageDestroy")
}
onForeground() {
console.info("MainAbility onForeground")
console.info("EntryAbility onForeground")
}
onBackground() {
console.info("MainAbility onBackground")
console.info("EntryAbility onBackground")
}
}
```
......
......@@ -25,7 +25,7 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol
- **Before starting a component of another application, verify the visible field of the target component.**
- This rule applies only to cross-application scenarios.
- If the **visible** field of the target component is **false**, verify the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- For details, see [Component Visible Configuration](../quick-start/module-configuration-file.md#abilities-tag)
- For details, see [Component Visible Configuration](../quick-start/module-configuration-file.md#abilities).
- **Before starting a component of a background application, verify the BACKGROUND permission.**
- An application is considered as a foreground application only when the application process gains focus or its UIAbility component is running in the foreground.
......@@ -67,4 +67,3 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol
![component-startup-rules](figures/component-startup-inter-fa.png)
<!--no_check-->
\ No newline at end of file
......@@ -24,7 +24,7 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol
- **Before starting a component of another application, verify the visible field of the target component.**
- If the **visible** field of the target component is **false**, verify the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- For details, see [Component Visible Configuration](../quick-start/module-configuration-file.md#abilities-tag)
- For details, see [Component Visible Configuration](../quick-start/module-configuration-file.md#abilities).
- **Before starting a component of a background application, verify the BACKGROUND permission.**
- An application is considered as a foreground application only when the application process gains focus or its UIAbility component is running in the foreground.
......@@ -62,4 +62,3 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol
![component-startup-rules](figures/component-startup-inter-stage.png)
<!--no_check-->
\ No newline at end of file
......@@ -4,4 +4,3 @@ The application configuration file contains information about the application co
The application project code developed based on the FA model contains a **config.json** file. For details about common configuration items, see [Application- or Component-Level Configuration](application-component-configuration-fa.md). For details about the file, see [Application Configuration File Overview (FA Model)](../quick-start/application-configuration-file-overview-fa.md).
<!--no_check-->
\ No newline at end of file
......@@ -4,4 +4,3 @@ The application configuration file contains information about the application co
The application project code developed based on the stage model contains one **app.json5** file and one or more **module.json5** files. For details about common configuration items, see [Application- or Component-Level Configuration (Stage Model)](application-component-configuration-stage.md). For details about the two files, see [Application Configuration File Overview (Stage Model)](../quick-start/application-configuration-file-overview-stage.md).
<!--no_check-->
\ No newline at end of file
......@@ -9,4 +9,3 @@ The stage model uses the [app.json5](../quick-start/app-configuration-file.md) a
**Figure 1** Configuration file differences
![comparison-of-configuration-file](figures/comparison-of-configuration-file.png)
<!--no_check-->
\ No newline at end of file
......@@ -30,7 +30,7 @@ export default {
```
After the PageAbility is created, its abilities-related configuration items are displayed in the **config.json** file. The following is an example **config.json** file of an ability named MainAbility:
After the PageAbility is created, its abilities-related configuration items are displayed in the **config.json** file. The following is an example **config.json** file of an ability named EntryAbility:
```json
{
......@@ -48,13 +48,13 @@ After the PageAbility is created, its abilities-related configuration items are
],
"orientation": "unspecified",
"visible": true,
"srcPath": "MainAbility",
"name": ".MainAbility",
"srcPath": "EntryAbility",
"name": ".EntryAbility",
"srcLanguage": "ets",
"icon": "$media:icon",
"description": "$string:MainAbility_desc",
"description": "$string:EntryAbility_desc",
"formsEnabled": false,
"label": "$string:MainAbility_label",
"label": "$string:EntryAbility_label",
"type": "page",
"launchType": "singleton"
}
......@@ -65,6 +65,7 @@ After the PageAbility is created, its abilities-related configuration items are
In the FA model, you can call **getContext** of **featureAbility** to obtain the application context and then use the capabilities provided by the context.
**Table 1** featureAbility APIs
| API| Description|
......
......@@ -59,4 +59,3 @@ The following is an example **config.json** file:
For details about the configuration items, see [Internal Structure of module](../quick-start/module-structure.md).
<!--no_check-->
\ No newline at end of file
# Matching Rules of Explicit Want and Implicit Want
Both explicit Want and implicit Want can be used to match an ability to start based on certain rules. These rules determine how the parameters set in Want match the configuration file declared by the target ability.
## Matching Rules of Explicit Want
The table below describes the matching rules of explicit Want.
- **Matching rules of explicit Want**
| Name| Type| Matching Item| Mandatory| Rule Description|
| -------- | -------- | -------- | -------- | -------- |
| deviceId | string | Yes| No| If this field is unspecified, only abilities on the local device are matched.|
| bundleName | string | Yes| Yes| If **abilityName** is specified but **bundleName** is unspecified, the matching fails.|
| moduleName | string | Yes| No| If this field is unspecified and multiple modules with the same ability name exist in the application, the first ability is matched by default.|
| abilityName | string | Yes| Yes| To use explicit Want, this field must be specified.|
| uri | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.|
| type | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.|
| action | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.|
| entities | Array&lt;string&gt; | No| No| This field is not used for matching. It is passed to the target ability as a parameter.|
| flags | number | No| No| This field is not used for matching and is directly transferred to the system for processing. It is generally used to set runtime information, such as URI data authorization.|
| Name| Type| Matching Item| Mandatory| Rule Description|
| -------- | -------- | -------- | -------- | -------- |
| deviceId | string | Yes| No| If this field is unspecified, only abilities on the local device are matched.|
| bundleName | string | Yes| Yes| If **abilityName** is specified but **bundleName** is unspecified, the matching fails.|
| moduleName | string | Yes| No| If this field is unspecified and multiple modules with the same ability name exist in the application, the first ability is matched by default.|
| abilityName | string | Yes| Yes| To use explicit Want, this field must be specified.|
| uri | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.|
| type | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.|
| action | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.|
| entities | Array&lt;string&gt; | No| No| This field is not used for matching. It is passed to the target ability as a parameter.|
| flags | number | No| No| This field is not used for matching and is directly transferred to the system for processing. It is generally used to set runtime information, such as URI data authorization.|
| parameters | {[key:&nbsp;string]:&nbsp;any} | No| No| This field is not used for matching. It is passed to the target ability as a parameter.|
- **Matching rules for implicit Want**
| Name| Type| Matching Item| Mandatory| Rule Description|
| -------- | -------- | -------- | -------- | -------- |
| deviceId | string | Yes| No| Implicit invoking is not supported across devices.|
| abilityName | string | No| No| To use implicit Want, this field must be left unspecified.|
| bundleName | string | Yes| No| - When only **bundleName** is specified, matching is limited to that application.<br>- When both **bundleName** and **moduleName** are specified, matching is limited to that module in that application.<br>- When only **moduleName** is specified, the setting is invalid.<br>For details, see [Interpretation of Implicit Want Matching Rules](#interpretation-of-implicit-want-matching-rules). |
| moduleName | string | Yes| No||
| uri | string | Yes| No||
| type | string | Yes| No||
| action | string | Yes| No||
| entities | Array&lt;string&gt; | Yes| No||
| flags | number | No| No| This field is not used for matching and is directly transferred to the system for processing. It is generally used to set runtime information, such as URI data authorization.|
| parameters | {[key:&nbsp;string]:&nbsp;any} | No| No| This field is not used for matching. It is passed to the target ability as a parameter.|
## Matching Rules for Implicit Want
## Interpretation of Implicit Want Matching Rules
The table below describes the matching rules of implicit Want.
| Name | Type | Matching Item| Mandatory| Rule Description |
| ----------- | ------------------------------ | ------ | ---- | ------------------------------------------------------------ |
| deviceId | string | Yes | No | Implicit invoking is not supported across devices. |
| abilityName | string | No | No | To use implicit Want, this field must be left unspecified. |
| bundleName | string | Yes | No | - When only **bundleName** is specified, matching is limited to that application.<br>- When both **bundleName** and **moduleName** are specified, matching is limited to that module in that application.<br>- When only **moduleName** is specified, the setting is invalid.<br> <br>These fields will be used for implicit matching.|
| moduleName | string | Yes | No | |
| uri | string | Yes | No | |
| type | string | Yes | No | |
| action | string | Yes | No | |
| entities | Array&lt;string&gt; | Yes | No | |
| flags | number | No | No | This field is not used for matching and is directly transferred to the system for processing. It is generally used to set runtime information, such as URI data authorization.|
| parameters | {[key:&nbsp;string]:&nbsp;any} | No | No | This field is not used for matching. It is passed to the target ability as a parameter. |
Get familiar with the following about implicit Want:
- The **want** parameter passed by the caller indicates the operation to be performed by the caller. It also provides data and application type restrictions.
- The **skills** field declares the capabilities of the target ability. For details, see [the skills tag](../quick-start/module-configuration-file.md#skills-tag) in the [module.json5 file](../quick-start/module-configuration-file.md).
- The **skills** field declares the capabilities of the target ability. For details, see [the skills tag](../quick-start/module-configuration-file.md#skills) in the [module.json5 file](../quick-start/module-configuration-file.md).
The system matches the **want** parameter (including the **action**, **entities**, **uri**, and **type** attributes) passed by the caller against the **skills** configuration (including the **actions**, **entities**, **uris**, and **type** attributes) of the abilities one by one. When all the four attributes are matched, a dialog box is displayed for users to select a matched application.
......@@ -60,8 +60,7 @@ The system matches the [action](../reference/apis/js-apis-ability-wantConstant.m
- If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an ability is specified but does not contain **action** in the passed **want** parameter, the matching fails.
Figure 1 Matching rules of action in the want parameter
**Figure 1** Matching rules of action in the want parameter
<img src="figures/want-action.png" alt="want-action" style="zoom:80%;" />
......@@ -112,6 +111,7 @@ There are four combinations of **uri** and **type** settings. The matching rules
To simplify the description, **uri** and **type** passed in the **want** parameter are called **w_uri** and **w_type**, respectively; the **uris** array under **skills** of an ability to match is called **s_uris**; each element in the array is called **s_uri**. Matching is performed from top to bottom.
Figure 4 Matching rules of uri and type in the want parameter
<img src="figures/want-uri-type2.png" alt="want-uri-type2" style="zoom:80%;" />
......@@ -158,5 +158,3 @@ To simplify the description, **uri** in the passed **want** parameter is called
- If the last character of **s_type** is the wildcard `*`, for example, `prefixType/*`, the matching is successful only when **w_type** contains `prefixType/`.
- If the last character of **w_type** is the wildcard `*`, for example, `prefixType/*`, the matching is successful only when **s_type** contains `prefixType/`.
<!--no_check-->
\ No newline at end of file
......@@ -345,21 +345,19 @@ The following describes how to implement multi-device collaboration through cros
3. Create the callee ability.
For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener.
For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener.
1. Configure the launch type of the UIAbility.
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**.|
An example of the UIAbility configuration is as follows:
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**.|
An example of the UIAbility configuration is as follows:
```json
"abilities":[{
"name": ".CalleeAbility",
......@@ -377,77 +375,75 @@ For the callee ability, implement the callback to receive data and the methods t
```ts
import Ability from '@ohos.app.ability.UIAbility';
```
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
export default class MySequenceable {
num: number = 0;
str: string = "";
num: number = 0
str: string = ""
constructor(num, string) {
this.num = num;
this.str = string;
this.num = num
this.str = string
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
return true;
messageParcel.writeInt(this.num)
messageParcel.writeString(this.str)
return true
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
return true;
this.num = messageParcel.readInt()
this.str = messageParcel.readString()
return true
}
}
```
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.
```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() {
try {
this.callee.off(MSG_SEND_METHOD);
} catch (error) {
console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`);
}
}
}
```
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.
```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() {
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.
1. Import the **UIAbility** module.
......@@ -457,14 +453,13 @@ For the callee ability, implement the callback to receive data and the methods t
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
async onButtonGetRemoteCaller() {
var caller = undefined;
var context = this.context;
var caller = undefined
var context = this.context
context.startAbilityByCall({
deviceId: getRemoteDeviceId(),
......@@ -472,23 +467,22 @@ For the callee ability, implement the callback to receive data and the methods t
abilityName: 'CalleeAbility'
}).then((data) => {
if (data != null) {
caller = data;
console.info('get remote caller success');
caller = data
console.info('get remote caller success')
// Register the onRelease() listener of the caller ability.
caller.onRelease((msg) => {
console.info(`remote caller onRelease is called ${msg}`);
console.info(`remote caller onRelease is called ${msg}`)
})
console.info('remote caller register OnRelease succeed');
console.info('remote caller register OnRelease succeed')
}
}).catch((error) => {
console.error(`get remote caller failed with ${error}`);
console.error(`get remote caller failed with ${error}`)
})
}
```
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.
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.
......
......@@ -31,4 +31,3 @@ Every mission retains a snapshot of the UIAbility instance. After the UIAbility
>
> The **specified** mode is supported in the stage model only.
<!--no_check-->
\ No newline at end of file
......@@ -14,4 +14,3 @@ Similar to a PageAbility, a ServiceAbility is configured in **abilities** under
For details about the configuration items, see [Internal Structure of module](../quick-start/module-structure.md).
<!--no_check-->
\ No newline at end of file
......@@ -293,4 +293,3 @@ The ServiceExtensionAbility component returns an IRemoteObject in the **onConnec
})
```
<!--no_check-->
\ No newline at end of file
......@@ -17,7 +17,7 @@ The following figure shows the basic concepts used in the stage model.
- ExtensionAbility is oriented to specific scenarios. You cannot derive directly from ExtensionAbility. Instead, use the derived classes of ExtensionAbility for your scenarios, such as FormExtensionAbility for widget scenarios, InputMethodExtensionAbility for input method scenarios, and WorkSchedulerExtensionAbility for Work Scheduled task scenarios. For example, to enable a user to create an application widget on the home screen, you must derive FormExtensionAbility, implement the callback functions, and configure the capability in the configuration file. The derived class instances are created by developers and their lifecycles are managed by the system. In the stage model, you must use the derived classes of ExtensionAbility to develop custom services based on your service scenarios.
- [WindowStage](../windowmanager/application-window-stage.md)
Each UIAbility class instance is bound to a WindowStage class instance, which functions as the window manager in the application process. The WindowStage class instance contains a main window. That is, UIAbility holds a window through WindowStage, and this window provides an area for ArkUI to render.
Each UIAbility class instance is bound to a WindowStage class instance, which functions as the window manager in the application process. The WindowStage class instance contains a main window. That is, UIAbility holds a main window through WindowStage, and this window provides an area for ArkUI to render.
- [Context](application-context-stage.md)
......@@ -32,12 +32,12 @@ The following figure shows the basic concepts used in the stage model.
During application development based on the stage model, the following tasks are involved in the application model.
**Table 1** Stage model development process
**Table 1** Stage model development process
| Task| Introduction| Guide|
| -------- | -------- | -------- |
| Application component development| Use the UIAbility and ExtensionAbility components of the stage model to develop applications.| - [Application- or Component-Level Configuration](application-component-configuration-stage.md)<br>- [UIAbility Component](uiability-overview.md)<br>- [ExtensionAbility Component](extensionability-overview.md)<br>- [AbilityStage Container Component](abilitystage.md)<br>- [Context](application-context-stage.md)<br>- [Component Startup Rules](component-startup-rules.md) |
| Application component development| Use the UIAbility and ExtensionAbility components of the stage model to develop applications.| - [Application- or Component-Level Configuration](application-component-configuration-stage.md)<br>- [UIAbility Component](uiability-overview.md)<br>- [ExtensionAbility Component](extensionability-overview.md)<br>- [AbilityStage Container Component](abilitystage.md)<br>- [Context](application-context-stage.md)<br>- [Component Startup Rules](component-startup-rules.md)|
| Inter-process communication (IPC)| Learn the process model and common IPC modes of the stage model.| - [Common Events](common-event-overview.md)<br>- [Background Services](background-services.md)|
| Inter-thread communication| Learn the thread model and common inter-thread communication modes of the stage model.| - [Emitter](itc-with-emitter.md)<br>- [Worker](itc-with-worker.md)|
| Mission management| Learn the basic concepts and typical scenarios of mission management in the stage model.| - [Mission Management Scenarios](mission-management-overview.md)<br>- [Mission Management and Launch Type](mission-management-launch-type.md)<br>- [Page Stack and MissionList](page-mission-stack.md) |
| Application configuration file| Learn the requirements for developing application configuration files in the stage model.| [Application Configuration File](config-file-stage.md) |
| Mission management| Learn the basic concepts and typical scenarios of mission management in the stage model.| - [Mission Management Scenarios](mission-management-overview.md)<br>- [Mission Management and Launch Type](mission-management-launch-type.md)<br>- [Page Stack and Mission List](page-mission-stack.md)|
| Application configuration file| Learn the requirements for developing application configuration files in the stage model.| [Application Configuration File](config-file-stage.md)|
......@@ -22,7 +22,7 @@ import featureAbility from '@ohos.ability.featureAbility'
want: {
bundleName: "com.example.myapplication",
moduleName: "entry",
abilityName: "com.example.myapplication.MainAbility"
abilityName: "com.example.myapplication.EntryAbility"
}
}
await featureAbility.startAbility(param)
......
......@@ -12,7 +12,7 @@ import featureAbility from '@ohos.ability.featureAbility';
async function restartAbility() {
let wantInfo = {
bundleName: "com.sample.MyApplication",
abilityName: "MainAbility",
abilityName: "EntryAbility",
parameters: {
page: "pages/second"
}
......@@ -89,7 +89,7 @@ struct Index {
featureAbility.startAbility({
want: {
bundleName: "com.exm.myapplication",
abilityName: "com.exm.myapplication.MainAbility",
abilityName: "com.exm.myapplication.EntryAbility",
parameters: { page: "pages/page1" }
}
}).then((data) => {
......@@ -104,7 +104,7 @@ struct Index {
featureAbility.startAbility({
want: {
bundleName: "com.exm.myapplication",
abilityName: "com.exm.myapplication.MainAbility",
abilityName: "com.exm.myapplication.EntryAbility",
parameters: { page: "pages/page2" }
}
}).then((data) => {
......
......@@ -9,23 +9,23 @@ This topic describes how the two application components of the stage model start
A UIAbility starts a PageAbility in the same way as it starts another UIAbility.
```ts
import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
export default class MainAbility extends UIAbility {
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
console.info("MainAbility onCreate")
console.info("EntryAbility onCreate")
}
onDestroy() {
console.info("MainAbility onDestroy")
console.info("EntryAbility onDestroy")
}
onWindowStageCreate(windowStage) {
console.info("MainAbility onWindowStageCreate")
console.info("EntryAbility onWindowStageCreate")
windowStage.loadContent('pages/Index', (err, data) => {
// ...
});
let want = {
bundleName: "com.ohos.fa",
abilityName: "MainAbility",
abilityName: "EntryAbility",
};
this.context.startAbility(want).then(() => {
console.info('Start Ability successfully.');
......@@ -34,13 +34,13 @@ export default class MainAbility extends UIAbility {
});
}
onWindowStageDestroy() {
console.info("MainAbility onWindowStageDestroy")
console.info("EntryAbility onWindowStageDestroy")
}
onForeground() {
console.info("MainAbility onForeground")
console.info("EntryAbility onForeground")
}
onBackground() {
console.info("MainAbility onBackground")
console.info("EntryAbility onBackground")
}
}
```
......@@ -54,23 +54,23 @@ A UIAbility starts a PageAbility through **startAbilityForResult()** in the same
```ts
import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
export default class MainAbility extends UIAbility {
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
console.info("MainAbility onCreate")
console.info("EntryAbility onCreate")
}
onDestroy() {
console.info("MainAbility onDestroy")
console.info("EntryAbility onDestroy")
}
onWindowStageCreate(windowStage) {
console.info("MainAbility onWindowStageCreate")
console.info("EntryAbility onWindowStageCreate")
windowStage.loadContent('pages/Index', (err, data) => {
// ...
});
let want = {
bundleName: "com.ohos.fa",
abilityName: "MainAbility",
abilityName: "EntryAbility",
};
this.context.startAbilityForResult(want).then((result) => {
console.info('Ability verify result: ' + JSON.stringify(result));
......@@ -79,13 +79,13 @@ export default class MainAbility extends UIAbility {
});
}
onWindowStageDestroy() {
console.info("MainAbility onWindowStageDestroy")
console.info("EntryAbility onWindowStageDestroy")
}
onForeground() {
console.info("MainAbility onForeground")
console.info("EntryAbility onForeground")
}
onBackground() {
console.info("MainAbility onBackground")
console.info("EntryAbility onBackground")
}
}
```
......@@ -110,7 +110,7 @@ export default class ServiceExtension extends Extension {
console.info("ServiceExtension onRequest")
let wantFA = {
bundleName: "com.ohos.fa",
abilityName: "MainAbility",
abilityName: "EntryAbility",
};
this.context.startAbility(wantFA).then(() => {
console.info('Start Ability successfully.');
......
......@@ -97,13 +97,13 @@ function getRemoteDeviceId() {
if (typeof dmClass === 'object' && dmClass != null) {
let list = dmClass.getTrustedDeviceListSync();
if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') {
console.info("MainAbility onButtonClick getRemoteDeviceId err: list is null");
console.info("EntryAbility onButtonClick getRemoteDeviceId err: list is null");
return;
}
console.info("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId);
console.info("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId);
return list[0].deviceId;
} else {
console.info("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null");
console.info("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null");
}
}
```
......
......@@ -14,7 +14,7 @@ import featureAbility from '@ohos.ability.featureAbility';
let parameter = {
"want": {
bundleName: "com.ohos.stage",
abilityName: "com.ohos.stage.MainAbility"
abilityName: "com.ohos.stage.EntryAbility"
}
};
featureAbility.startAbility(parameter).then((code) => {
......@@ -38,7 +38,7 @@ import featureAbility from '@ohos.ability.featureAbility';
let parameter = {
"want": {
bundleName: "com.ohos.stage",
abilityName: "com.ohos.stage.MainAbility"
abilityName: "com.ohos.stage.EntryAbility"
}
};
featureAbility.startAbilityForResult(parameter).then((result) => {
......@@ -60,7 +60,7 @@ import particleAbility from '@ohos.ability.particleAbility';
let parameter = {
"want": {
bundleName: "com.ohos.stage",
abilityName: "com.ohos.stage.MainAbility"
abilityName: "com.ohos.stage.EntryAbility"
}
};
particleAbility.startAbility(parameter).then(() => {
......
# Interaction Intra-Device Between UIAbility Components
# Intra-Device Interaction Between UIAbility Components
UIAbility is the minimum unit that can be scheduled by the system. Jumping between functional modules in a device involves starting of specific UIAbility components, which belong to the same or a different application (for example, starting UIAbility of a third-party payment application).
......@@ -50,7 +50,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import Window from '@ohos.window';
import window from '@ohos.window';
export default class FuncAbility extends UIAbility {
onCreate(want, launchParam) {
......@@ -196,6 +196,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.
<img src="figures/uiability-intra-device-interaction.png" alt="uiability-intra-device-interaction" style="zoom:50%;" />
3. To stop the **UIAbility** instance after the document application is used, call **terminateSelf()**.
......@@ -442,7 +443,8 @@ Ability call is usually used in the following scenarios:
The following figure shows the ability call process.
Figure 1 Ability call process
**Figure 1** Ability call process
<img src="figures/call.png" alt="call" style="zoom:67%;" />
- The caller ability uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the callee ability.
......@@ -461,7 +463,7 @@ Figure 1 Ability call process
The following table describes the main APIs used for the ability call. For details, see [AbilityContext](../reference/apis/js-apis-app-ability-uiAbility.md#caller).
**Table 2** Ability call APIs
**Table 2** Ability call APIs
| API| Description|
| -------- | -------- |
......@@ -486,8 +488,7 @@ For the callee ability, implement the callback to receive data and the methods t
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|
| -------- | -------- |
......@@ -595,9 +596,9 @@ An example of the ability configuration is as follows:
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.
```ts
// Register the onRelease() listener of the caller ability.
private regOnRelease(caller) {
......
......@@ -18,6 +18,7 @@ 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**.
**Figure 1** Demonstration effect in singleton mode
<img src="figures/uiability-launch-type1.png" alt="uiability-launch-type1" width="40%;" />
> **NOTE**
......@@ -47,6 +48,7 @@ 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**.
**Figure 2** Demonstration effect in standard mode
<img src="figures/standard-mode.png" alt="standard-mode" width="40%;" />
To use the standard mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **standard**.
......@@ -72,6 +74,7 @@ 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.
**Figure 3** Demonstration effect in specified mode
<img src="figures/uiability-launch-type2.png" alt="uiability-launch-type2" style="zoom:50%;" />
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.
......@@ -93,7 +96,7 @@ 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.
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 instances.
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
// Configure an independent key for each UIAbility instance.
......@@ -146,7 +149,8 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of
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.
The following steps are used as an example.
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.
......
......@@ -7,7 +7,7 @@ When a user opens, switches, and returns to an application, the UIAbility instan
The lifecycle of UIAbility has four states: **Create**, **Foreground**, **Background**, and **Destroy**, as shown in the figure below.
**Figure 1** UIAbility lifecycle states
**Figure 1** UIAbility lifecycle states
<img src="figures/Ability-Life-Cycle.png" alt="Ability-Life-Cycle" style="zoom:50%;" />
......@@ -21,7 +21,7 @@ The **Create** state is triggered when the UIAbility instance is created during
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import Window from '@ohos.window';
import window from '@ohos.window';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
......@@ -36,14 +36,14 @@ export default class EntryAbility extends UIAbility {
After the UIAbility instance is created but before it enters the **Foreground** state, the system creates a WindowStage instance and triggers the **onWindowStageCreate()** callback. You can set UI loading and WindowStage event subscription in the callback.
**Figure 2** WindowStageCreate and WindowStageDestory
**Figure 2** WindowStageCreate and WindowStageDestory
<img src="figures/Ability-Life-Cycle-WindowStage.png" alt="Ability-Life-Cycle-WindowStage" style="zoom:50%;" />
In the **onWindowStageCreate()** callback, use [loadContent()](../reference/apis/js-apis-window.md#loadcontent9-2) to set the page to be loaded, and call [on('windowStageEvent')](../reference/apis/js-apis-window.md#onwindowstageevent9) to subscribe to [WindowStage events](../reference/apis/js-apis-window.md#windowstageeventtype9), for example, having or losing focus, or becoming visible or invisible.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import Window from '@ohos.window';
import window from '@ohos.window';
export default class EntryAbility extends UIAbility {
// ...
......@@ -77,7 +77,7 @@ Before the UIAbility instance is destroyed, the **onWindowStageDestroy()** callb
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import Window from '@ohos.window';
import window from '@ohos.window';
export default class EntryAbility extends UIAbility {
// ...
......@@ -135,7 +135,7 @@ The UIAbility instance is destroyed when **terminateSelf()** is called or the us
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import Window from '@ohos.window';
import window from '@ohos.window';
export default class EntryAbility extends UIAbility {
// ...
......
......@@ -37,4 +37,3 @@ To enable an application to properly use a UIAbility component, declare the UIAb
>
> 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).
<!--no_check-->
\ No newline at end of file
......@@ -11,10 +11,10 @@ If no startup page is specified, a white screen occurs after the application is
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import Window from '@ohos.window';
import window from '@ohos.window';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: Window.WindowStage) {
onWindowStageCreate(windowStage: window.WindowStage) {
// Main window is created. Set a main page for this ability.
windowStage.loadContent('pages/Index', (err, data) => {
// ...
......
......@@ -23,7 +23,7 @@
```
- **Implicit Want**: A type of Want with **abilityName** unspecified when starting the ability.
Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills-tag)) provided by another application. For example, you can use implicit Want to describe a request for opening a link, since you do not care which application is used to open the link. The system matches all applications that support the request.
Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills)) provided by another application. For example, you can use implicit Want to describe a request for opening a link, since you do not care which application is used to open the link. The system matches all applications that support the request.
```ts
......@@ -47,5 +47,3 @@
> - If the **want** parameter passed does not contain **abilityName** or **bundleName**, the ServiceExtensionAbility components of all applications cannot be started through implicit Want.
>
> - If the **want** parameter passed contains **bundleName**, the **startServiceExtensionAbility()** method can be used to implicitly start ServiceExtensionAbility. By default, ServiceExtensionAbility with the highest priority is returned. If all the matching ServiceExtensionAbility components have the same priority, the first ServiceExtensionAbility is returned.
<!--no_check-->
\ No newline at end of file
......@@ -232,7 +232,7 @@ The widget configuration file is named **config.json**. Find the **config.json**
"type": "service",
"srcLanguage": "ets",
"formsEnabled": true,
"formConfigAbility": "ability://com.example.entry.MainAbility",
"formConfigAbility": "ability://com.example.entry.EntryAbility",
"forms": [{
"colorMode": "auto",
"defaultDimension": "2*2",
......@@ -434,7 +434,7 @@ You can use the web-like paradigm (HML+CSS+JSON) to develop JS widget pages. Thi
"actions": {
"routerEvent": {
"action": "router",
"abilityName": "com.example.entry.MainAbility",
"abilityName": "com.example.entry.EntryAbility",
"params": {
"message": "add detail"
}
......@@ -452,8 +452,8 @@ You can set router and message events for components on a widget. The router eve
2. Set the router event.
- **action**: **router**, which indicates a router event.
- **abilityName**: name of the ability to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default MainAbility name of the FA model created by DevEco Studio is com.example.entry.MainAbility.
- **params**: custom parameters passed to the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the main ability in the FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field.
- **abilityName**: name of the ability to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name created by DevEco Studio in the FA model is com.example.entry.EntryAbility.
- **params**: custom parameters passed to the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the EntryAbility in the FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field.
3. Set the message event.
- **action**: **message**, which indicates a message event.
......@@ -529,7 +529,7 @@ The following is an example:
"actions": {
"routerEvent": {
"action": "router",
"abilityName": "com.example.entry.MainAbility",
"abilityName": "com.example.entry.EntryAbility",
"params": {
"message": "add detail"
}
......
......@@ -597,4 +597,3 @@ The following is an example:
};
```
<!--no_check-->
\ No newline at end of file
# IPC & RPC Development<a name="EN-US_TOPIC_0000001103710988"></a>
# IPC & RPC Development Guidelines
## When to Use<a name="section18502174174019"></a>
## When to Use
IPC/RPC enables a proxy and a stub that run on different processes to communicate with each other, regardless of whether they run on the same or different devices.
## Available APIs<a name="section1633115419401"></a>
**Table 1** Native IPC APIs
## Available APIs
| Class/Interface | Function | Description |
| --------------- | -------- | ----------- |
| [IRemoteBroker](../reference/apis/js-apis-rpc.md#iremotebroker) | sptr<IRemoteObject> AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. |
| IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) | Called to process a request from the proxy and return the result. Derived classes need to override this method. |
| IRemoteProxy | | Service proxy classes are derived from the **IRemoteProxy** class. |
Table 1 Native IPC APIs
## How to Develop<a name="section4207112818418"></a>
| Class| API| Description|
| -------- | -------- | -------- |
| [IRemoteBroker](../reference/apis/js-apis-rpc.md#iremotebroker) | sptr&lt;IRemoteObject&gt; AsObject() | Holder of a remote proxy object. If you call this API on the stub, the **RemoteObject** is returned; if you call this API on the proxy, the proxy object is returned.|
| IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &amp;data, MessageParcel &amp;reply, MessageOption &amp;option) | Callback used to process a request from the proxy and return the result. Derived classes need to override this API.|
| IRemoteProxy | | Service proxy class, which is derived from the **IRemoteProxy** class.|
**Using Native APIs**
1. Define the IPC interface **ITestAbility**.
## How to Develop
**ITestAbility** inherits the IPC base class **IRemoteBroker** and defines descriptors, functions, and message code. The functions need to be implemented on both the proxy and stub.
### **Using Native APIs**
```
class ITestAbility : public IRemoteBroker {
public:
1. Add dependencies.
SDK dependency:
```
#IPC scenario
external_deps = [
"ipc:ipc_single",
]
#RPC scenario
external_deps = [
"ipc:ipc_core",
]
```
In addition, the refbase implementation on which IPC/RPC depends is stored in **//utils**. Add the dependency on the Utils source code.
```
external_deps = [
"c_utils:utils",
]
```
2. Define the IPC interface **ITestAbility**.
**ITestAbility** inherits the IPC base class **IRemoteBroker** and defines descriptors, functions, and message code. The functions need to be implemented on both the proxy and stub.
```c++
#include "iremote_broker.h"
// Define message codes.
const int TRANS_ID_PING_ABILITY = 5
const std::string DESCRIPTOR = "test.ITestAbility";
class ITestAbility : public IRemoteBroker {
public:
// DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string.
DECLARE_INTERFACE_DESCRIPTOR(u"test.ITestAbility");
int TRANS_ID_PING_ABILITY = 1; // Define the message code.
DECLARE_INTERFACE_DESCRIPTOR(to_utf16(DESCRIPTOR));
virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions.
};
```
};
```
2. Define and implement service provider **TestAbilityStub**.
3. Define and implement service provider **TestAbilityStub**.
This class is related to the IPC framework and needs to inherit **IRemoteStub<ITestAbility\>**. You need to override **OnRemoteRequest** on the stub to receive requests from the proxy.
This class is related to the IPC framework and needs to inherit **IRemoteStub&lt;ITestAbility&gt;**. You need to override **OnRemoteRequest** on the stub to receive requests from the proxy.
```
class TestAbilityStub : public IRemoteStub<ITestAbility> {
public:
virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
int TestPingAbility(const std::u16string &dummy) override;
```c++
#include "iability_test.h"
#include "iremote_stub.h"
class TestAbilityStub : public IRemoteStub<ITestAbility> {
public:
virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
int TestPingAbility(const std::u16string &dummy) override;
};
int TestServiceStub::OnRemoteRequest(uint32_t code,
MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
switch (code) {
case TRANS_ID_PING_ABILITY: {
std::u16string dummy = data.ReadString16();
int result = TestPingAbility(dummy);
reply.WriteInt32(result);
return 0;
}
default:
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
}
```
3. Define the **TestAbility** class that implements functions for the stub.
```
class TestAbility : public TestAbilityStub {
public:
int TestPingAbility(const std::u16string &dummy);
}
int TestAbility::TestPingAbility(const std::u16string &dummy) {
return 0;
}
```
4. Define and implement **TestAbilityProxy**.
This class is implemented on the proxy and inherits **IRemoteProxy<ITestAbility\>**. You can call **SendRequest** to send a request to the stub and expose the capabilities provided by the stub.
```
class TestAbilityProxy : public IRemoteProxy<ITestAbility> {
public:
explicit TestAbilityProxy(const sptr<IRemoteObject> &impl);
int TestPingService(const std::u16string &dummy) override;
private:
static inline BrokerDelegator<TestAbilityProxy> delegator_; // Use the iface_cast macro.
}
TestAbilityProxy::TestAbilityProxy(const sptr<IRemoteObject> &impl)
: IRemoteProxy<ITestAbility>(impl)
{
}
int TestAbilityProxy::TestPingService(const std::u16string &dummy) {
MessageOption option;
MessageParcel dataParcel, replyParcel;
dataParcel.WriteString16(dummy);
int error = Remote()->SendRequest(TRANS_ID_PING_ABILITY, dataParcel, replyParcel, option);
int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1;
return result;
}
```
5. Register and start an SA.
Call **AddSystemAbility** to register the **TestAbilityStub** instance of the SA with **SystemAbilityManager**. The registration parameters vary depending on whether the **SystemAbilityManager** resides on the same device as the SA.
```
// Register the TestAbilityStub instance with the SystemAbilityManager on the same device as the SA.
auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
samgr->AddSystemAbility(saId, new TestAbility());
// Register the TestAbilityStub instance with the SystemAbilityManager on a different device.
auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
ISystemAbilityManager::SAExtraProp saExtra;
saExtra.isDistributed = true; // Set a distributed SA.
int result = samgr->AddSystemAbility(saId, new TestAbility(), saExtra);
```
6. Obtain the SA.
Call the **GetSystemAbility** function of the **SystemAbilityManager** class to obtain the **IRemoteObject** for the SA, and create a **TestAbilityProxy** instance.
```
// Obtain the proxy of the SA registered on the local device.
sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(saId);
sptr<ITestAbility> testAbility = iface_cast<ITestAbility>(remoteObject); // Use the iface_cast macro to convert the proxy to a specific type.
// Obtain the proxies of the SAs registered with other devices.
sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(saId, deviceId); // deviceId identifies a device.
sptr<TestAbilityProxy> proxy(new TestAbilityProxy(remoteObject)); // Construct a proxy.
```
int TestAbilityStub::OnRemoteRequest(uint32_t code,
MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
switch (code) {
case TRANS_ID_PING_ABILITY: {
std::u16string dummy = data.ReadString16();
int result = TestPingAbility(dummy);
reply.WriteInt32(result);
return 0;
}
default:
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
}
```
4. Define the **TestAbility** class that implements functions for the stub.
```c++
#include "iability_server_test.h"
class TestAbility : public TestAbilityStub {
public:
int TestPingAbility(const std::u16string &dummy);
}
int TestAbility::TestPingAbility(const std::u16string &dummy) {
return 0;
}
```
5. Define and implement **TestAbilityProxy**.
This class is implemented on the proxy and inherits **IRemoteProxy&lt;ITestAbility&gt;**. You can call **SendRequest** to send a request to the stub and expose the capabilities provided by the stub.
```c++
#include "iability_test.h"
#include "iremote_proxy.h"
#include "iremote_object.h"
class TestAbilityProxy : public IRemoteProxy<ITestAbility> {
public:
explicit TestAbilityProxy(const sptr<IRemoteObject> &impl);
int TestPingAbility(const std::u16string &dummy) override;
private:
static inline BrokerDelegator<TestAbilityProxy> delegator_; // Use the iface_cast macro.
}
TestAbilityProxy::TestAbilityProxy(const sptr<IRemoteObject> &impl)
: IRemoteProxy<ITestAbility>(impl)
{
}
int TestAbilityProxy::TestPingAbility(const std::u16string &dummy){
MessageOption option;
MessageParcel dataParcel, replyParcel;
dataParcel.WriteString16(dummy);
int error = Remote()->SendRequest(TRANS_ID_PING_ABILITY, dataParcel, replyParcel, option);
int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1;
return result;
}
```
6. Register and start an SA.
Call **AddSystemAbility** to register the **TestAbilityStub** instance of the SA with **SystemAbilityManager**. The registration parameters vary depending on whether the **SystemAbilityManager** resides on the same device as the SA.
```c++
// Register the TestAbilityStub instance with the SystemAbilityManager on the same device as the SA.
auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
samgr->AddSystemAbility(saId, new TestAbility());
// Register the TestAbilityStub instance with the SystemAbilityManager on a different device.
auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
ISystemAbilityManager::SAExtraProp saExtra;
saExtra.isDistributed = true; // Set a distributed SA.
int result = samgr->AddSystemAbility(saId, new TestAbility(), saExtra);
```
7. Obtain the SA.
Call the **GetSystemAbility** function of the **SystemAbilityManager** class to obtain the **IRemoteObject** for the SA, and create a **TestAbilityProxy** instance.
```c++
// Obtain the proxy of the SA registered on the local device.
sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(saId);
sptr<ITestAbility> testAbility = iface_cast<ITestAbility>(remoteObject); // Use the iface_cast macro to convert the proxy to a specific type.
// Obtain the proxy of the SA registered with any other devices.
sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
// networkId is the device identifier and can be obtained through GetLocalNodeDeviceInfo.
sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(saId, networkId);
sptr<TestAbilityProxy> proxy(new TestAbilityProxy(remoteObject)); // Construct a proxy.
```
### **Using JS APIs**
1. Add dependencies.
```ts
import rpc from "@ohos.rpc"
import featureAbility from "@ohos.ability.featureAbility"
```
2. Bind the desired ability.
Construct the **want** variable, and specify the bundle name and component name of the application where the ability is located. If cross-device communication is involved, also specify the network ID of the target device, which can be obtained through **deviceManager**. Then, construct the **connect** variable, and specify the callback that is called when the binding is successful, the binding fails, or the ability is disconnected. After that, call the API provided by **featureAbility** to bind an ability.
```ts
import rpc from "@ohos.rpc"
import featureAbility from "@ohos.ability.featureAbility"
let proxy = null
let connectId = null
// Bind the ability on a single device.
let want = {
// Enter the bundle name and ability name.
"bundleName": "ohos.rpc.test.server",
"abilityName": "ohos.rpc.test.server.ServiceAbility",
}
let connect = {
onConnect:function(elementName, remote) {
proxy = remote
},
onDisconnect:function(elementName) {
},
onFailed:function() {
proxy = null
}
}
connectId = featureAbility.connectAbility(want, connect)
// If you're binding the ability across devices, use deviceManager to obtain the network ID of the target device.
import deviceManager from '@ohos.distributedHardware.deviceManager'
function deviceManagerCallback(deviceManager) {
let deviceList = deviceManager.getTrustedDeviceListSync()
let networkId = deviceList[0].networkId
let want = {
"bundleName": "ohos.rpc.test.server",
"abilityName": "ohos.rpc.test.service.ServiceAbility",
"networkId": networkId,
"flags": 256
}
connectId = featureAbility.connectAbility(want, connect)
}
// The first parameter specifies the bundle name of the application, and the second parameter specifies the callback used to return the device ID obtained by using DeviceManager.
deviceManager.createDeviceManager("ohos.rpc.test", deviceManagerCallback)
```
3. Process requests sent from the client.
Call the **onConnect** API to return a proxy object inherited from **rpc.RemoteObject** after the ability is successfully bound. Implement the **onRemoteMessageRequest** API for the proxy object to process requests sent from the client.
```ts
onConnect(want: Want) {
var robj:rpc.RemoteObject = new Stub("rpcTestAbility")
return robj
}
class Stub extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor)
}
onRemoteMessageRequest(code, data, reply, option) {
// Process requests sent from the client based on the code.
return true
}
}
```
4. Process responses sent from the server.
Obtain the proxy object from the **onConnect** callback, call **sendRequestAsync** to send a request, and receive the response using a callback or a promise (an object representing the eventual completion or failure of an asynchronous operation and its result value).
```ts
// Use a promise.
let option = new rpc.MessageOption()
let data = rpc.MessageParcel.create()
let reply = rpc.MessageParcel.create()
// Write parameters to data.
proxy.sendRequestAsync(1, data, reply, option)
.then(function(result) {
if (result.errCode != 0) {
console.error("send request failed, errCode: " + result.errCode)
return
}
// Read the result from result.reply.
})
.catch(function(e) {
console.error("send request got exception: " + e)
}
.finally(() => {
data.reclaim()
reply.reclaim()
})
// Use a callback.
function sendRequestCallback(result) {
try {
if (result.errCode != 0) {
console.error("send request failed, errCode: " + result.errCode)
return
}
// Read the result from result.reply.
} finally {
result.data.reclaim()
result.reply.reclaim()
}
}
let option = new rpc.MessageOption()
let data = rpc.MessageParcel.create()
let reply = rpc.MessageParcel.create()
// Write parameters to data.
proxy.sendRequest(1, data, reply, option, sendRequestCallback)
```
5. Tear down the connection.
Use the API provided by **featureAbility** to tear down the connection when the communication is over.
```ts
import rpc from "@ohos.rpc"
import featureAbility from "@ohos.ability.featureAbility"
function disconnectCallback() {
console.info("disconnect ability done")
}
featureAbility.disconnectAbility(connectId, disconnectCallback)
```
......@@ -3,20 +3,42 @@
## Basic Concepts
Inter-process communication (IPC) and remote procedure call (RPC) are used to implement cross-process communication. IPC uses the Binder driver to implement inter-process communication within a device, whereas RPC uses the intelligent software bus driver to implement inter-process communication across devices.
The inter-process communication (IPC) and remote procedure call (RPC) mechanisms are used to implement cross-process communication. The difference between them lies in that IPC uses the Binder driver to implement cross-process communication within a device, whereas RPC uses the DSoftBus driver to implement cross-process communication across devices.
IPC and RPC generally use the client-server model for communication. The client (service requester) obtains the proxy of the server (service provider) and uses this proxy to read and write data. The server registers system abilities (SAs) with the system ability manager (SAMgr), which manages the SAs and provides interfaces for clients. To interact with an SA, the client must obtain the proxy of the SA from SAMgr.
The reason why cross-process communication is needed is that each process has its own independent resources and memory space and one process is not allowed to access the resources and memory space of other processes. IPC and RPC usually use the client-server model, where the client (service requester, that is, the process that requests a service) obtains the proxy of the server (service provider, that is, the process that provides the service) and uses the proxy to read and write data to implement data communication across processes. More specifically, the client constructs a proxy object of the server. The proxy object has the same functions as the server. To access a certain API of the server, you only need to access the corresponding API in the proxy object. The proxy object sends the request to the server, and the server processes the received request and returns the processing result to the proxy object through the driver. Then, the proxy object forwards the processing result to the client. The server registers system abilities (SAs) with the system ability manager (SAMgr), which manages the SAs and provides APIs for clients. To communicate with a specific SA, the client must obtain the proxy of the SA from SAMgr.
In OpenHarmony documents, proxy represents the service requester, and stub represents the service provider.
In the following sections, proxy represents the service requester, and stub represents the service provider.
![IPC&RPC communication mechanisms](figures/IPC_RPC_communication.PNG)
## Constraints
- The data transmitted for inter-process communication within a device cannot exceed 1 MB. If more data needs to be transmitted, use the anonymous shared memory.
- During cross-process communication within a single device, the maximum amount of data to be transmitted is about 1 MB. If the amount of data to be transmitted exceeds this limit, use the [anonymous shared memory](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-rpc.md#ashmem8).
- Subscription to death notifications of anonymous stub objects (not registered with SAMgr) is prohibited in RPC.
- During cross-process communication across processes, a proxy object cannot be passed back to the device that hosts the stub object pointed by the proxy object. That is, the proxy object pointing to the stub object of the remote device cannot be passed across processes twice on the local device.
## **Recommendations**
First, compile an API class and define message codes in the API class for both communication parties to identify operations. Unimplemented APIs are allowed in the API class because it must be inherited by both communication parties and its inheritance classes cannot be abstract classes. When inheriting the API class, both communication parties must implement the unimplemented APIs, so as to make sure that the inheritance classes are not abstract classes.
Then, implement the API class specific to the stub, and override the **AsObject** and **OnRemoteRequest** APIs. In addition, compile the proxy to implement the APIs in the API class and override the **AsObject** API. You can also encapsulate an additional API for calling **SendRequest** to send data to the peer.
After the preceding operations are done, register a system ability (SA) with SAMgr. Note that the registration should be completed in the process that hosts the stub. Then, obtain the proxy from SAMgr as needed to implement cross-process communication with the stub.
Related steps are as follows:
- Implementing the API class: Inherit **IRemoteBroker**, define message codes, and declare APIs that are not implemented in the API class.
- Implementing the service provider (stub): Inherit **IRemoteStub** or **RemoteObject**, and override the **AsObject** and **OnRemoteRequest** APIs.
- Implementing the service requester (proxy): Inherit **IRemoteProxy** or **RemoteProxy**, override the **AsObject** API, and encapsulate the required API to call **SendRequest**.
- Registering the SA: Apply for a unique ID for the SA, and register the SA with SAMgr.
- The cross-device proxy object cannot be passed to the device hosting the stub object pointed by this proxy object.
- Obtaining the SA: Obtain the proxy based on the SA ID and device ID, and use the proxy to communicate with the remote end.
## Related Modules
[Distributed Scheduler](https://gitee.com/openharmony/ability_dmsfwk)
[Distributed Ability Manager Service Framework](https://gitee.com/openharmony/ability_dmsfwk)
# Subscribing to State Changes of a Remote Object
IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **DeathRecipient** callback and the **onRemoteDied** method to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network.
IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **DeathRecipient** interface and the **onRemoteDied** API to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network. It is worth noting that these APIs should be called in the following order: The proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered.
Note that the proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered.
## When to Use
This subscription mechanism is applicable when the local proxy object needs to detect death of the process hosting the remote stub object or network detach of the device hosting the remote stub object. When the proxy detects death of the remote stub object, the proxy can clear local resources. Currently, IPC supports death notification for anonymous objects, but RPC does not. That is, you can only subscribe to death notifications of services that have been registered with SAMgr.
## **Using Native APIs**
## **Development Using Native APIs**
| API| Return Value Type| Feature Description|
| -------- | -------- | -------- |
| AddDeathRecipient(const sptr\<DeathRecipient> &recipient); | bool | Adds a recipient for death notifications of a remote stub object.|
| RemoveDeathRecipient(const sptr\<DeathRecipient> &recipient); | bool | Removes the recipient for death notifications of a remote stub object.|
| OnRemoteDied(const wptr\<IRemoteObject> &object); | void | Called when the remote stub object dies.|
| API| Description|
| -------- | -------- |
| AddDeathRecipient(const sptr\<DeathRecipient> &recipient); | Adds a recipient for death notifications of a remote stub object.|
| RemoveDeathRecipient(const sptr\<DeathRecipient> &recipient); | Removes the recipient for death notifications of a remote stub object.|
| OnRemoteDied(const wptr\<IRemoteObject> &object); | Called when the remote stub object dies.|
### Sample Code
```C++
#include "iremote_broker.h"
#include "iremote_stub.h"
## Sample Code
// Define message codes.
enum {
TRANS_ID_PING_ABILITY = 5,
TRANS_ID_REVERSED_MONITOR
};
const std::string DESCRIPTOR = "test.ITestAbility";
class ITestService : public IRemoteBroker {
public:
// DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string.
DECLARE_INTERFACE_DESCRIPTOR(to_utf16(DESCRIPTOR));
virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions.
};
class TestServiceProxy : public IRemoteProxy<ITestAbility> {
public:
explicit TestAbilityProxy(const sptr<IRemoteObject> &impl);
virtual int TestPingAbility(const std::u16string &dummy) override;
int TestAnonymousStub();
private:
static inline BrokerDelegator<TestAbilityProxy> delegator_; // Use the iface_cast macro.
};
TestServiceProxy::TestServiceProxy(const sptr<IRemoteObject> &impl)
: IRemoteProxy<ITestAbility>(impl)
{
}
int TestServiceProxy::TestPingAbility(const std::u16string &dummy){
MessageOption option;
MessageParcel dataParcel, replyParcel;
dataParcel.WriteString16(dummy);
int error = PeerHolder::Remote()->SendRequest(TRANS_ID_PING_ABILITY, dataParcel, replyParcel, option);
int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1;
return result;
}
```
```c++
#include "iremote_object.h"
class TestDeathRecipient : public IRemoteObject::DeathRecipient {
public:
virtual void OnRemoteDied(const wptr<IRemoteObject>& remoteObject);
}
void TestDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remoteObject)
{
}
```
```c++
sptr<IPCObjectProxy> object = new IPCObjectProxy(1, to_utf16(DESCRIPTOR));
sptr<IRemoteObject::DeathRecipient> deathRecipient (new TestDeathRecipient());// Construct a death notification recipient.
bool result = proxy->AddDeathRecipient(deathRecipient); // Add a recipient for death notifications.
result = proxy->RemoveDeathRecipient(deathRecipient); // Remove the recipient for death notifications.
bool result = object->AddDeathRecipient(deathRecipient); // Add a recipient for death notifications.
result = object->RemoveDeathRecipient(deathRecipient); // Remove the recipient for death notifications.
```
## **Using JS APIs**
| API | Return Value Type| Feature Description |
| -------------------- | ---------- | ------------------------------------------------------------ |
| addDeathRecippient | boolean | Adds a recipient for death notifications of the remote object, including death notifications of the remote proxy.|
| removeDeathRecipient | boolean | Removes the recipient for death notifications of the remote object. |
| onRemoteDied | void | Called to perform subsequent operations when a death notification of the remote object is received.|
### Sample Code
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
}
}
let deathRecipient = new MyDeathRecipient();
proxy.addDeathRecippient(deathRecipient, 0);
proxy.removeDeathRecipient(deathRecipient, 0);
```
## Reverse Death Notification (Anonymous Stub)
Forward dead notification is a mechanism that allows the proxy to detect death notifications of the stub. To achieve reverse dead notification, we can leverage the forward dead notification mechanism to allow the stub to detect death notifications of the proxy.
Suppose there are two processes, A (the process hosting the original stub) and B (the process hosting the original proxy). After obtaining the proxy object of process A, process B creates an anonymous stub object (that is, a stub object not registered with SAMgr), which can be called a callback stub. Then, process B calls **SendRequest** to send the callback stub to the original stub of process A. As a result, process A obtains the callback proxy of process B. When process B dies or the device hosting process B detaches from the network, the callback stub dies. The callback proxy detects the death of the callback stub and sends a death notification to the original stub. In this way, reverse death notification is implemented.
> NOTE
> - Reverse death notification can only be used for cross-process communication within a device.
> - When an anonymous stub object is not pointed by any proxy, the kernel automatically reclaims the object.
### Sample Code
```c++
// Proxy
int TestAbilityProxy::TestAnonymousStub()
{
MessageOption option;
MessageParcel dataParcel, replyParcel;
dataParcel.UpdateDataVersion(Remote());
dataParcel.WriteRemoteObject(new TestAbilityStub());
int error = Remote()->SendRequest(TRANS_ID_REVERSED_MONITOR,dataParcel, replyParcel, option);
int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1;
return result;
}
// Stub
int TestAbilityStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
switch (code) {
case TRANS_ID_REVERSED_MONITOR: {
sptr<IRemoteObject> obj = data.ReadRemoteObject();
if (obj == nullptr) {
reply.WriteInt32(ERR_NULL_OBJECT);
return ERR_NULL_OBJECT;
}
bool result = obj->AddDeathRecipient(new TestDeathRecipient());
result ? reply.WriteInt32(ERR_NONE) : reply.WriteInt32(-1);
break;
}
default:
break;
}
return ERR_NONE;
}
```
......@@ -10,42 +10,40 @@ The geographic description helps users understand a location easily by providing
## Available APIs
The following table describes APIs available for mutual conversion between coordinates and geographic description. For details, see [Geolocation Manager](../reference/apis/js-apis-geolocation.md).
The following table describes APIs available for mutual conversion between coordinates and geographic description. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
**Table1** APIs for geocoding and reverse geocoding
| API | Description |
| -------- | -------- |
| isGeoServiceAvailable(callback: AsyncCallback&lt;boolean&gt;) : void | Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result.|
| isGeoServiceAvailable() : Promise&lt;boolean&gt; | Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result.|
| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;) : void | Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. |
| getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise&lt;Array&lt;GeoAddress&gt;&gt; | Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;) : void | Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest) : Promise&lt;Array&lt;GeoAddress&gt;&gt; | Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. |
| isGeocoderAvailable(): boolean; | Checks whether the (reverse) geocoding service is available.|
| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;): void | Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. |
| getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise&lt;Array&lt;GeoAddress&gt;&gt; | Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;): void | Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest): Promise&lt;Array&lt;GeoAddress&gt;&gt; | Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. |
## How to Develop
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> The **GeoConvert** instance needs to access backend services to obtain information. Therefore, before performing the following steps, ensure that your device is connected to the network.
1. Import the **geolocation** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities.
1. Import the **geoLocationManager** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities.
```ts
import geolocation from '@ohos.geolocation';
import geoLocationManager from '@ohos.geolocation';
```
2. Query whether geocoder service is available.
- Call **isGeoServiceAvailable** to query whether the geocoder service is available. If the service is available, continue with step 3.
```ts
geolocation.isGeoServiceAvailable((err, data) => {
if (err) {
console.log('isGeoServiceAvailable err: ' + JSON.stringify(err));
} else {
console.log('isGeoServiceAvailable data: ' + JSON.stringify(data));
}
});
import geoLocationManager from '@ohos.geoLocationManager';
try {
var isAvailable = geoLocationManager.isGeocoderAvailable();
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
3. Obtain the conversion result.
......@@ -53,13 +51,17 @@ The following table describes APIs available for mutual conversion between coord
```ts
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
if (err) {
console.log('getAddressesFromLocation err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocation data: ' + JSON.stringify(data));
}
});
try {
geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
if (err) {
console.log('getAddressesFromLocation err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocation data: ' + JSON.stringify(data));
}
});
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
Your application can obtain the **GeoAddress** list that matches the specified coordinates and then read location information from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md).
......@@ -67,13 +69,17 @@ The following table describes APIs available for mutual conversion between coord
```ts
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => {
if (err) {
console.log('getAddressesFromLocationName err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocationName data: ' + JSON.stringify(data));
}
});
try {
geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => {
if (err) {
console.log('getAddressesFromLocationName err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocationName data: ' + JSON.stringify(data));
}
});
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md).
......
......@@ -10,11 +10,11 @@ Real-time location of the device is recommended for location-sensitive services.
## Available APIs
For details about the APIs used to obtain the device location information, see [Geolocation Manager](../reference/apis/js-apis-geolocation.md).
For details about the APIs used to obtain the device location information, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
## How to Develop
To learn more about the APIs for obtaining device location information, see [Geolocation](../reference/apis/js-apis-geolocation.md).
To learn more about the APIs for obtaining device location information, see [Geolocation](../reference/apis/js-apis-geoLocationManager.md).
1. Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user as described below.
The system provides the following location permissions:
......@@ -41,10 +41,10 @@ To learn more about the APIs for obtaining device location information, see [Geo
You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md).
2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities.
2. Import the **geoLocationManager** module by which you can implement all APIs related to the basic location capabilities.
```
import geolocation from '@ohos.geolocation';
```ts
import geoLocationManager from '@ohos.geolocation';
```
3. Instantiate the **LocationRequest** object. This object provides APIs to notify the system of the location service type and the interval of reporting location information.<br>
......@@ -78,7 +78,7 @@ To learn more about the APIs for obtaining device location information, see [Geo
Sample code for initializing **requestInfo** for navigation:
```ts
var requestInfo = {'scenario': geolocation.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
var requestInfo = {'scenario': geoLocationManager.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
```
**Method 2:**
......@@ -107,7 +107,7 @@ To learn more about the APIs for obtaining device location information, see [Geo
Sample code for initializing **requestInfo** for the location accuracy priority policy:
```ts
var requestInfo = {'priority': geolocation.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
var requestInfo = {'priority': geoLocationManager.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
```
4. Instantiate the **Callback** object for the system to report location results.
......@@ -122,25 +122,24 @@ To learn more about the APIs for obtaining device location information, see [Geo
5. Start device location.
```ts
geolocation.on('locationChange', requestInfo, locationChange);
geoLocationManager.on('locationChange', requestInfo, locationChange);
```
6. (Optional) Stop device location.
```ts
geolocation.off('locationChange', locationChange);
geoLocationManager.off('locationChange', locationChange);
```
If your application does not need the real-time device location, it can use the last known device location cached in the system instead.
```ts
geolocation.getLastLocation((err, data) => {
if (err) {
console.log('getLastLocation: err: ' + JSON.stringify(err));
} else {
console.log('getLastLocation: data: ' + JSON.stringify(data));
}
});
import geoLocationManager from '@ohos.geoLocationManager';
try {
var location = geoLocationManager.getLastLocation();
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
To call this method, your application needs to request the **ohos.permission.LOCATION** permission from the user.
......@@ -40,8 +40,8 @@ try {
// 1. Obtain the list of input devices and check whether a physical keyboard is connected.
inputDevice.getDeviceList().then(data => {
for (let i = 0; i < data.length; ++i) {
inputDevice.getKeyboardType(data[i]).then(res => {
if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD) {
inputDevice.getKeyboardType(data[i]).then(type => {
if (type === inputDevice.KeyboardType.ALPHABETIC_KEYBOARD) {
// The physical keyboard is connected.
isPhysicalKeyboardExist = true;
}
......@@ -53,7 +53,7 @@ try {
console.log(`Device event info: ${JSON.stringify(data)}`);
inputDevice.getKeyboardType(data.deviceId, (error, type) => {
console.log("The keyboard type is: " + type);
if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') {
if (type === inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') {
// The physical keyboard is inserted.
isPhysicalKeyboardExist = true;
} else if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'remove') {
......
......@@ -7,7 +7,7 @@ Mouse pointer management provides the functions such as displaying or hiding the
## Modules to Import
```js
import inputDevice from '@ohos.multimodalInput.pointer';
import pointer from '@ohos.multimodalInput.pointer';
```
## Available APIs
......
......@@ -14,11 +14,10 @@ The following table lists the USB APIs currently available. For details, see the
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| hasRight(deviceName: string): boolean | Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise. |
| requestRight(deviceName: string): Promise\<boolean> | Requests the temporary permission for a given application to access the USB device. |
| removeRight(deviceName: string): boolean | Removes the permission for a given application to access the USB device. |
| connectDevice(device: USBDevice): Readonly\<USBDevicePipe> | Connects to the USB device based on the device information returned by `getDevices()`. |
| getDevices(): Array<Readonly\<USBDevice>> | Obtains the USB device list. |
| hasRight(deviceName: string): boolean | Checks whether the user has the device access permissions. |
| requestRight(deviceName: string): Promise\<boolean> | Requests the temporary permission for a given application to access the USB device. This API uses a promise to return the result. |
| connectDevice(device: USBDevice): Readonly\<USBDevicePipe> | Connects to the USB device based on the device list returned by `getDevices()`. |
| getDevices(): Array<Readonly\<USBDevice>> | Obtains the list of USB devices connected to the USB host. If no USB device is connected, an empty list is returned. |
| setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. |
| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. |
| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface. |
......@@ -37,7 +36,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat
```js
// Import the USB API package.
import usb from '@ohos.usb';
import usb from '@ohos.usbV9';
// Obtain the USB device list.
let deviceList = usb.getDevices();
/*
......
......@@ -60,7 +60,7 @@ Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Configure the **startWindowIcon** attribute under **abilities** in the **module.json5** file.
Reference: [Application Package Structure Configuration File](../quick-start/stage-structure.md)
Reference: [Application Package Structure (Stage Model)](../quick-start/module-configuration-file.md)
Example:
......@@ -83,17 +83,15 @@ Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Implement the **onConfigurationUpdated** callback in the **Ability** class. The callback is triggered when the system language, color mode, or display parameters (such as the orientation and density) change.
Reference: [Ability Development](../ability/stage-ability.md)
## Can I obtain the context through globalThis in the stage model?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Do not use **globalThis** to obtain the context in the stage model. This is because all the processes of an application share a JS VM instance in the stage model. Multiple abilities can run on these processes and share the same global object. If **globalThis** is used, the context of different abilities of the same JS VM instance may be returned.
For details about the recommended operation, see [Context in the Stage Model](../ability/context-userguide.md#context-in-the-stage-model).
Reference of the recommended operation: [Context (Stage Model)](../application-models/application-context-stage.md)
## How do I obtain the HAP file installation path of application B from application A?
## How do I obtain the HAP installation path of application B from application A?
Applicable to: OpenHarmony SDK 3.0 or later, stage model of API version 9
......@@ -109,7 +107,7 @@ The callee uses **AbilityContext.terminateSelfWithResult** to destroy its abilit
Applicable to: OpenHarmony SDK 3.2.5.5, FA model of API version 8
After a widget is added, the **onCreate()** lifecycle is triggered so that related user information (silent login) can be displayed even when the application is not started. However, users must manually add the widget after the application is installed.
After a widget is added, the **oncreate()** lifecycle is triggered so that related user information (silent login) can be displayed even when the application is not started. However, users must manually add the widget after the application is installed.
## How do I obtain the context?
......@@ -214,3 +212,5 @@ The following conditions must be met:
1. Before the redirection to the previous page, a confirm dialog box will be displayed. Note that **router.disableAlertBeforeBackPage** is used to disable the display of a confirm dialog box before returning to the previous page (default), and **router.enableAlertBeforeBackPage** is used to enable the display.
2. The system return key is used.
<!--no_check-->
\ No newline at end of file
......@@ -3,4 +3,7 @@
- [MediaLibrary Overview](medialibrary-overview.md)
- [Media Asset Management](medialibrary-resource-guidelines.md)
- [File Path Management](medialibrary-filepath-guidelines.md)
- [Album Management](medialibrary-album-guidelines.md)
\ No newline at end of file
- [Album Management](medialibrary-album-guidelines.md)
- File Access Framework
- [File Access Framework Overview](file-access-framework-overview.md)
# File Access Framework Overview
On devices running OpenHarmony 3.2 (API version 9) or later, applications can access public files on the local device, remote device, and external storage device, as well as files shared by multiple users, based on the File Access Framework (FAF).
To ensure user data privacy, this framework allows users to create, open, delete, rename, and move files on the file access server only through the **File Manager** and **File Picker** applications.
The user data of an application is stored on the device even after the application is uninstalled.
If a system application needs to access public files on the local device, use [File Path Management](medialibrary-filepath-guidelines.md).
> **NOTE**
> 1. For a non-management system application, for example, **Gallery**, use the **mediaLibrary** APIs for direct file operation.
> 2. In principle, do not mix use the FAF APIs with the mediaLibrary APIs.
## FAF Mechanism
Based on the OpenHarmony [ExtensionAbility mechanism](../application-models/extensionability-overview.md), the FAF provides unified APIs for external systems. With these APIs, applications can preview and operate public files to implement their own logic.
You can visit the [source repository](https://gitee.com/openharmony/filemanagement_user_file_service) for more details.
The following figure shows the FAF-based file operation process.
**Figure 1** Hierarchy of public file operations
![](figures/public-file-operation.png)
- **File access client**: an application that needs to access or operate public files. By starting the file selector application, it enables users to perform file operations on the UI.
- **File selector application**: a system application that allows users to access all shared datasets. You can use the FAF APIs to operate the datasets.
- **File access server**: a service that supports dataset sharing in the system. Currently, [UserFileManager](https://gitee.com/openharmony/multimedia_medialibrary_standard) and ExternalFileManager are available. UserFileManager manages datasets on local disks and distributed devices, and ExternalFileManager manages datasets on external storage devices such as SD cards and USB flash drives. You can also share your own datasets based on the FAF server configuration.
The FAF has the following features:
- Users can browse the datasets provided by all file server applications in the system, rather than those provided by a single application.
- The file access client can operate files through the file selector application, without obtaining the permission to use the FAF.
- Multiple temporarily mounted devices, such as external storage cards and distributed devices, can be accessed at the same time.
## Data Models
Data models in the FAF are transferred through URI, FileInfo, and RootInfo. For details, see [fileExtension](../reference/apis/js-apis-fileExtensionInfo.md). Applications on the file access server can use the **FileAccessExtensionAbility** APIs to securely share their data.
**Figure 2** Data flow of the public file access framework
![](figures/faf-data-flow.png)
NOTE
- In the FAF, the file access client does not directly interact with the file access server. The client only needs to have the permission to start the file selector application.
- The file selector application provides a standard document access UI for users, even if the underlying file access servers differ greatly.
......@@ -69,7 +69,7 @@ You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to o
**How to Develop**
1. Call [Context.getFilesDir](../reference/apis/js-apis-Context.md#contextgetfilesdir) to obtain the directory of the application sandbox.
1. Call [Context.getFilesDir](../reference/apis/js-apis-inner-app-context.md#contextgetfilesdir) to obtain the directory of the application sandbox.
2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory.
3. Call **fileio.open** to open the file in the sandbox.
4. Call **fileAsset.open** to open the file in the public directory.
......
......@@ -3,27 +3,30 @@
## Introduction
**AudioRenderer** provides APIs for rendering audio files and controlling playback. It also supports audio interruption. You can use the APIs provided by **AudioRenderer** to play audio files in output devices and manage playback tasks.
Before calling the APIs, be familiar with the following terms:
- **Audio interruption**: When an audio stream with a higher priority needs to be played, the audio renderer interrupts the stream with a lower priority. For example, if a call comes in when the user is listening to music, the music playback, which is the lower priority stream, is paused.
- **Status check**: During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioRenderer** instance. This is because some operations can be performed only when the audio renderer is in a given state. If the application performs an operation when the audio renderer is not in the given state, the system may throw an exception or generate other undefined behavior.
- **Asynchronous operation**: To prevent the UI thread from being blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8).
- **Audio interruption mode**: OpenHarmony provides two audio interruption modes: **shared mode** and **independent mode**. In shared mode, all **AudioRenderer** instances created by the same application share one focus object, and there is no focus transfer inside the application. Therefore, no callback will be triggered. In independent mode, each **AudioRenderer** instance has an independent focus object, and focus preemption occurs. Focus preemption triggers focus transfer, and the **AudioRenderer** instance that originally has the focus receives a notification through the callback. By default, the shared mode is used. You can call **setInterruptMode()** to set the independent mode.
- **Audio interruption mode**: OpenHarmony provides two audio interruption modes: **shared mode** and **independent mode**. In shared mode, all **AudioRenderer** instances created by the same application share one focus object, and there is no focus transfer inside the application. Therefore, no callback will be triggered. In independent mode, each **AudioRenderer** instance has an independent focus object, and focus transfer is triggered by focus preemption. When focus transfer occurs, the **AudioRenderer** instance that is having the focus receives a notification through the callback. By default, the shared mode is used. You can call **setInterruptMode()** to switch to the independent mode.
## Working Principles
The following figure shows the audio renderer state transitions.
Figure 1 Audio renderer state transitions
**Figure 1** Audio renderer state transitions
![audio-renderer-state](figures/audio-renderer-state.png)
- **PREPARED**: The audio renderer enters this state by calling **create()**.
- **RUNNING**: The audio renderer enters this state by calling **start()** when it is in the **PREPARED** state or by calling **start()** when it is in the **STOPPED** state.
- **PAUSED**: The audio renderer in the **RUNNING** state can call **pause()** to pause the audio playback. After the audio playback is paused, it can call **start()** to resume the playback.
- **STOPPED**: The audio renderer in the **PAUSED** or **RUNNING** state can call **stop()** to stop the playback.
- **RELEASED**: The audio renderer in the **PREPARED**, **PAUSED**, or **STOPPED** state can use **release()** to release all occupied hardware and software resources. It will not transit to any other state after it enters the **RELEASED** state.
- **PAUSED**: The audio renderer enters this state by calling **pause()** when it is in the **RUNNING** state. When the audio playback is paused, it can call **start()** to resume the playback.
- **STOPPED**: The audio renderer enters this state by calling **stop()** when it is in the **PAUSED** or **RUNNING** state.
- **RELEASED**: The audio renderer enters this state by calling **release()** when it is in the **PREPARED**, **PAUSED**, or **STOPPED** state. In this state, the audio renderer releases all occupied hardware and software resources and will not transit to any other state.
## How to Develop
......@@ -62,7 +65,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
```js
async function startRenderer() {
let state = audioRenderer.state;
// The audio renderer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state after being started.
// The audio renderer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state when start() is called.
if (state != audio.AudioState.STATE_PREPARED && state != audio.AudioState.STATE_PAUSED &&
state != audio.AudioState.STATE_STOPPED) {
console.info('Renderer is not in a correct state to start');
......@@ -258,8 +261,8 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
let interruptMode : audio.InterruptMode = audio.InterruptMode.SHARE_MODE;
await audioRenderer.setInterruptMode(interruptMode);
// Set the volume of the stream to 10.
let volume : number = 10;
// Set the volume of the stream to 0.5.
let volume : number = 0.5;
await audioRenderer.setVolume(volume);
```
......@@ -303,7 +306,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
case audio.InterruptHint.INTERRUPT_HINT_RESUME:
startRenderer();
break;
// Notify the application that the audio stream is interrupted. The application determines whether to continue. (In this example, the application pauses the rendering.)
// Notify the application that the audio stream is interrupted. The application then determines whether to continue. (In this example, the application pauses the rendering.)
case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
isPlay = false;
pauseRenderer();
......@@ -312,7 +315,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
}
});
audioRenderer.off('audioInterrupt'); // Unsubscribe from the audio interruption event. This event will no longer be received.
audioRenderer.off('audioInterrupt'); // Unsubscribe from the audio interruption event. This event will no longer be listened for.
```
10. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event.
......@@ -358,7 +361,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
```js
try {
audioRenderer.on('invalidInput', () => { // The string does not match.
audioRenderer.on('invalidInput', () => { // The string is invalid.
})
} catch (err) {
console.info(`Call on function error, ${err}`); // The application throws exception 401.
......@@ -373,7 +376,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
14. (Optional) Refer to the complete example of **on('audioInterrupt')**.
Create **AudioRender1** and **AudioRender2** in an application, configure the independent interruption mode, and call **on('audioInterrupt')** to subscribe to audio interruption events. At the beginning, **AudioRender1** has the focus. When **AudioRender2** attempts to obtain the focus, **AudioRenderer1** receives a focus transfer notification and the related log information is printed. If the shared mode is used, the log information will not be printed during application running.
Create **AudioRender1** and **AudioRender2** in an application, configure the independent interruption mode, and call **on('audioInterrupt')** to subscribe to audio interruption events. At the beginning, **AudioRender1** has the focus. When **AudioRender2** attempts to obtain the focus, **AudioRender1** receives a focus transfer notification and the related log information is printed. If the shared mode is used, the log information will not be printed during application running.
```js
async runningAudioRender1(){
......@@ -429,7 +432,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
let rlen = 0;
rlen += bufferSize;
// 1.7 Render the original audio data in the buffer by using audioRenderer.
// 1.7 Render the original audio data in the buffer by using audioRender.
let id = setInterval(async () => {
if (audioRenderer1.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state.
ss1.closeSync();
......@@ -505,7 +508,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
let rlen = 0;
rlen += bufferSize;
// 2.7 Render the original audio data in the buffer by using audioRenderer.
// 2.7 Render the original audio data in the buffer by using audioRender.
let id = setInterval(async () => {
if (audioRenderer2.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state.
ss2.closeSync();
......
......@@ -61,7 +61,7 @@ The development process consists of the following main steps:
The required model can be downloaded directly or obtained using the model conversion tool.
- If the downloaded model is in the `.ms` format, you can use it directly for inference. The following uses the **mobilenetv2.ms** model as an example.
- If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/en/r1.5/use/benchmark_tool.html) to convert it to the `.ms` format.
- If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/zh-CN/r1.5/use/downloads.html#id1) to convert it to the `.ms` format.
2. Create a context, and set parameters such as the number of runtime threads and device type.
......
# Agent-Powered Scheduled Reminder Development
## When to Use
You can set your application to call the **ReminderRequest** class to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background, even when your application is frozen or exits.
## Available APIs
**reminderAgent** encapsulates the APIs for publishing and canceling reminders.
For details about the APIs, see [reminderAgent](../reference/apis/js-apis-reminderAgent.md).
**Table 1** Major APIs in reminderAgent
| Name| Description|
| -------- | -------- |
| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback&lt;number&gt;): void<br>publishReminder(reminderReq: ReminderRequest): Promise&lt;number&gt; | Publishes a scheduled reminder.<br>The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system. |
| cancelReminder(reminderId: number, callback: AsyncCallback&lt;void&gt;): void<br>cancelReminder(reminderId: number): Promise&lt;void&gt; | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)|
| getValidReminders(callback: AsyncCallback&lt;Array&lt;ReminderRequest&gt;&gt;): void<br>getValidReminders(): Promise&lt;Array&lt;ReminderRequest&gt;&gt; | Obtains all valid reminders set by the current application.|
| cancelAllReminders(callback: AsyncCallback&lt;void&gt;): void<br>cancelAllReminders(): Promise&lt;void&gt; | Cancels all reminders set by the current application.|
| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback&lt;void&gt;): void<br>addNotificationSlot(slot: NotificationSlot): Promise&lt;void&gt; | Registers a **NotificationSlot** instance to be used by the reminder.|
| removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback&lt;void&gt;): void<br>removeNotificationSlot(slotType: notification.SlotType): Promise&lt;void&gt; | Removes a **NotificationSlot** instance of a specified type.|
## How to Develop
> **NOTE**
>
> 1. To publish a reminder through the reminder agent, your application needs to apply for the **ohos.permission.PUBLISH_AGENT_REMINDER** permission.
>
> 2. Your application must have notification enabled. For details, see [Notification.requestEnableNotification](../reference/apis/js-apis-notification.md#notificationrequestenablenotification8).
1. Define a reminder agent.
Sample code for defining a reminder agent for a countdown timer:
```js
import reminderAgent from '@ohos.reminderAgent';
import notification from '@ohos.notification';
export default {
// ArkTS project:
let timer : reminderAgent.ReminderRequestTimer = {
reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER,
triggerTimeInSeconds: 10,
actionButton: [
{
title: "close",
type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE
}
],
wantAgent: {
pkgName: "com.example.device",
abilityName: "com.example.device.MainAbility"
},
maxScreenWantAgent: {
pkgName: "com.example.device",
abilityName: "com.example.device.MainAbility"
},
title: "this is title",
content: "this is content",
expiredContent: "this reminder has expired",
notificationId: 100,
slotType: notification.SlotType.SOCIAL_COMMUNICATION
}
}
```
Sample code for defining a reminder agent for a calendar event:
```js
// ArkTS project:
let calendar : reminderAgent.ReminderRequestCalendar = {
reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR,
dateTime: {
year: 2050,
month: 7,
day: 30,
hour: 11,
minute: 14,
second: 30
},
repeatMonths: [1],
repeatDays: [1],
actionButton: [
{
title: "close",
type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE
},
{
title: "snooze",
type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE
},
],
wantAgent: {
pkgName: "com.example.device",
abilityName: "com.example.device.MainAbility"
},
maxScreenWantAgent: {
pkgName: "com.example.device",
abilityName: "com.example.device.MainAbility"
},
ringDuration: 5,
snoozeTimes: 2,
timeInterval: 5,
title: "this is title",
content: "this is content",
expiredContent: "this reminder has expired",
snoozeContent: "remind later",
notificationId: 100,
slotType: notification.SlotType.SOCIAL_COMMUNICATION
}
```
Sample code for defining a reminder agent for an alarm:
```js
// ArkTS project:
let alarm : reminderAgent.ReminderRequestAlarm = {
reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM,
hour: 11,
minute: 14,
daysOfWeek: [0],
actionButton: [
{
title: "close",
type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE
},
{
title: "snooze",
type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE
},
],
wantAgent: {
pkgName: "com.example.device",
abilityName: "com.example.device.MainAbility"
},
maxScreenWantAgent: {
pkgName: "com.example.device",
abilityName: "com.example.device.MainAbility"
},
ringDuration: 5,
snoozeTimes: 2,
timeInterval: 5,
title: "this is title",
content: "this is content",
expiredContent: "this reminder has expired",
snoozeContent: "remind later",
notificationId: 100,
slotType: notification.SlotType.SOCIAL_COMMUNICATION
}
```
2. Publish a countdown reminder.
```js
startTimer() {
reminderAgent.publishReminder(this.timer, (err, reminderId) =>{
this.printInfo(JSON.stringify(err));
this.printInfo("reminderId:" + reminderId);
});
}
```
HML page code:
```html
<div class="container">
<button type="text" value="publishReminder" onclick="startTimer"></button>
</div>
```
# Agent-Powered Scheduled Reminder Overview
Your application can call the **ReminderRequest** class to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background, even when your application is frozen or exits.
......@@ -5,11 +5,30 @@
- [Getting Started with ArkTS in FA Model](start-with-ets-fa.md)
- [Getting Started with JavaScript in FA Model](start-with-js-fa.md)
- Development Fundamentals
- [Application Package Structure Configuration File (FA Model)](package-structure.md)
- [Application Package Structure Configuration File (Stage Model)](stage-structure.md)
- [SysCap](syscap.md)
- Application Package Fundamentals
- [Application Package Overview](application-package-overview.md)
- Application Package Structure
- [Application Package Structure in Stage Model](application-package-structure-stage.md)
- [Application Package Structure in FA Model](application-package-structure-fa.md)
- [HAR File Structure](har-structure.md)
- Multi-HAP Mechanism
- [Multi-HAP Design Objectives](multi-hap-objective.md)
- [Multi-HAP Build View](multi-hap-build-view.md)
- [Multi-HAP Development, Debugging, Release, and Deployment Process](multi-hap-release-deployment.md)
- [Multi-HAP Usage Rules](multi-hap-rules.md)
- [Multi-HAP Operation Mechanism and Data Communication Modes](multi-hap-principles.md)
- [Application Installation and Uninstallation Process](application-package-install-uninstall.md)
- Application Configuration Files in Stage Model
- [Application Configuration File Overview (Stage Model)](application-configuration-file-overview-stage.md)
- [app.json5 Configuration File](app-configuration-file.md)
- [module.json5 Configuration File](module-configuration-file.md)
- Application Configuration Files in FA Model
- [Application Configuration File Overview (FA Model)](application-configuration-file-overview-fa.md)
- [Internal Structure of the app Tag](app-structure.md)
- [Internal Structure of deviceConfig Tag](deviceconfig-structure.md)
- [Internal Structure of the module Tag](module-structure.md)
- [Resource Categories and Access](resource-categories-and-access.md)
- Learning ArkTS
- Learning ArkTS
- [Getting Started with ArkTS](arkts-get-started.md)
- ArkTS Syntax (Declarative UI)
- [Basic UI Description](arkts-basic-ui-description.md)
......
# app.json5 Configuration File
This document gives an overview of the **app.json5** configuration file. To start with, let's go through an example of what this file contains.
```json
{
"app": {
"bundleName": "com.application.myapplication",
"vendor": "example",
"versionCode": 1000000,
"versionName": "1.0.0",
"icon": "$media:app_icon",
"label": "$string:app_name",
"description": "$string:description_application",
"distributedNotificationEnabled": true,
"minAPIVersion": 9,
"targetAPIVersion": 9,
"apiReleaseType": "Release",
"debug": false,
"entityType": "media",
"car": {
"minAPIVersion": 8,
}
},
}
```
As shown above, the **app.json5** file contains several tags.
**Table 1** Tags in the app.json5 file
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| bundleName | Bundle name, which uniquely identifies an application. The value must comply with the following rules:<br>- Consists of letters, digits, underscores (_), and periods (.).<br>- Starts with a letter.<br>- Contains 7 to 127 bytes.<br>You are advised to use the reverse domain name notation, for example, *com.example.demo*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.<br>If an application is built with the system source code, you are advised to name it in *com.ohos.demo* notation, where **ohos** signifies that the application is an OpenHarmony system application.| String| No|
| debug | Whether the application can be debugged. This tag is generated during compilation and building in DevEco Studio.<br>- **true**: The application can be debugged.<br>- **false**: The application cannot be debugged.| Boolean| Yes (initial value: **false**)|
| icon | [Icon of the application](../application-models/application-component-configuration-stage.md). The value is an icon resource index. | String| No|
| label | [Name of the application](../application-models/application-component-configuration-stage.md). The value is a string resource index. | String| No|
| description | Description of the application. The value is a string with a maximum of 255 bytes or a resource index to the description. | String| Yes (initial value: left empty)|
| vendor | Vendor of the application. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)|
| versionCode | Version number of the application. The value is a 32-bit non-negative integer less than 2 to the power of 31. It is used only to determine whether a version is later than another version. A larger value indicates a later version. Ensure that a new version of the application uses a value greater than any of its predecessors. | Number| No|
| versionName | Version number of the application displayed to users.<br>The value consists of only digits and dots. The four-part format *A.B.C.D* is recommended, wherein:<br>Part 1 (*A*): major version number, which ranges from 0 to 99. A major version consists of major new features or large changes.<br>Part 2 (*B*): minor version number, which ranges from 0 to 99. A minor version consists of some new features and large bug fixes.<br>Part 3 (*C*): feature version number, which ranges from 0 to 99. A feature version consists of scheduled new features.<br>Part 4 (*D*): maintenance release number or patch number, which ranges from 0 to 999. A maintenance release or patch consists of resolution to security flaws or minor bugs.<br>The value contains a maximum of 127 bytes.| String| No|
| minCompatibleVersionCode | Minimum compatible version of the application. It is used to check whether the application is compatible with a version on other devices in the cross-device scenario.| Number| Yes (initial value: value of **versionCode**)|
| minAPIVersion | Minimum API version required for running the application.| Number| Yes (initial value: value of **compatibleSdkVersion** in **bundle-profile.json5**)|
| targetAPIVersion | Target API version required for running the application.| Number| Yes (initial value: value of **compileSdkVersion** in **bundle-profile.json5**)|
| apiReleaseType | Type of the target API version required for running the application. The value can be **"CanaryN"**, **"BetaN"**, or **"Release"**, where **N** represents a positive integer.<br>- **Canary**: indicates a restricted release.<br>- **Beta**: indicates a publicly released beta version.<br>- **Release**: indicates a publicly released official version.<br>The value is set by DevEco Studio reading the stage of the SDK in use.| String| Yes (initial value: set by DevEco Studio)|
| distributedNotificationEnabled | Whether distributed notification is enabled for the application. When distributed notification is enabled and device A and device B where the application is installed are on the same distributed network, the devices behave in this way: If device A receives a message, device B will receive a distributed notification prompting the user to check the message received on device A.<br>- **true**: Distributed notification is enabled.<br>- **false**: Distributed notification is not enabled.| Boolean| Yes (initial value: **false**)|
| entityType | Type of the application. The options are as follows:<br>- game<br>- media<br>- communication<br>- news<br>- travel<br>- utility<br>- shopping<br>- education<br>- kids<br>- business<br>- photography<br>- unspecified| String| Yes (initial value: **"unspecified"**)|
| multiProjects | Whether the application supports joint development of multiple projects.<br>- **true**: The application supports joint development of multiple projects.<br>- **false**: The application does not support joint development of multiple projects.| Boolean| Yes (initial value: **false**)|
| tablet | Tablet-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.<br>When running on tablets, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)|
| tv | TV-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.<br>When running on TVs, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)|
| wearable | Wearable-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.<br>When running on wearables, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)|
| car | Head unit–specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.<br>When running on head units, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)|
| default | Default device–specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.<br>When running on default devices, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)|
# Internal Structure of the app Tag
The **app** tag contains application-wide configuration. The internal structure is as follows:
### Internal Structure of the app Tag
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| bundleName | Bundle name, which uniquely identifies an application. The bundle name must start with a letter and can contain only letters, digits, underscores (_), and periods (.). The bundle name is a string with 7 to 127 bytes of a reverse domain name, for example, **"com.example.myapplication"**. It is recommended that the first level be the domain suffix "com" and the second level be the vendor/individual name. More levels are also accepted.| String| No|
| vendor | Vendor of the application. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)|
|version | Version of the application.| Object| No|
| apiVersion | OpenHarmony API version on which the application depends.| Object| Yes (initial value: left empty)|
| smartWindowSize | Screen size used when the application runs in the emulator.| String| Yes (initial value: left empty)|
| smartWindowDeviceType | Types of emulated devcies on which the application can run.| String array| Yes (initial value: left empty)|
#### Internal Structure of the version Atttribute
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| name | Application version number displayed to users. The value can be customized and cannot exceed 127 bytes. The configuration rules are as follows:<br>For API version 5 and earlier versions, use the three-part format *A.B.C* (compatible with a two-part format *A.B*), where A, B, and C are integers ranging from 0 to 999.<br>*A* indicates the major version number.<br>*B* indicates the minor version number.<br>*C* indicates the patch version number. For API version 6 and later versions, the four-part format *A.B.C.D* is recommended, where A, B, and C are integers ranging from 0 to 99, and D is an integer ranging from 0 to 999.<br>*A* indicates the major version number.<br>*B* indicates the minor version number.<br>*C* indicates the feature version number.<br>*D* indicates the patch version number.| Number| No|
| code | Application version number used only for application management by OpenHarmony. This version number is not visible to users of the application. The configuration rules are as follows:<br>API version 5 and earlier versions: The value is a non-negative integer within 32 binary digits, which needs to be converted from the value of **version.name**. The conversion rule is as follows: Value of **code** = A * 1,000,000 + B * 1,000 + C. For example, if the value of **version.name** is 2.2.1, the value of **code** is 2002001. API version 6 and later versions: The value of **code** is not associated with the value of **version.name** and can be customized. The value is a non-negative integer less than 2 to the power of 31. Note that the value must be updated each time the application version is updated, and the value for a later version must be greater than that for an earlier version.| Number| No|
| minCompatibleVersionCode | Earliest version compatible with the application. It is used in the cross-device scenario to check whether the application is compatible with a specific version on other devices. The value rules are the same as those of **version.code**.| Number| No (initial value: value of **code**)|
#### Internal Structure of the apiVersion Attribute
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| compatible | Minimum API version required for running the application. The value ranges from 0 to 2147483647.| Number| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)|
| target | Target API version required for running the application. The value ranges from 0 to 2147483647.| Number| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)|
| releaseType | SDK status when the application is running.<br>**canary**: preliminary release open only to specific developers. This release does not promise API stability and may require tolerance of instability.<br>**beta**: release open to all developers. This release does not promise API stability and may require tolerance of instability. After several releases, the beta version is declared as an API stability milestone through Release Notes, and APIs of later versions are frozen.<br>**release**: official release open to all developers. This release promises that all APIs are stable. When a version is in this state, the **Stage** field is not displayed in the version number.| String| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)|
### Example of the **app** Tag
```json
"app": {
"bundleName": "com.example.myapplication",
"vendor": "example",
"version": {
"code": 8,
"name": "8.0.1"
},
"apiVersion": {
"compatible": 8,
"target": 9,
"releaseType": "Beta1"
}
}
```
# Application Configuration File Overview (FA Model)
Each application project must have configuration files in its code directory. These configuration files provide basic application information for OpenHarmony build tools, the operating system, and application markets.
The application configuration file must contain the following information:
- Basic information of the application, including the bundle name, vendor, and version number. Such information must be set under the **app** tag.
- Component information of the application, including all abilities, device types, component types, and syntax types in use.
- Device-specific information of the application. Such information affects the functioning of the application on the device.
When developing an application in the Feature Ability (FA) model, you must declare the package structure of the application in the **config.json** file.
## Configuration File Internal Structure
The **config.json** file consists of three mandatory tags, namely, **app**, **deviceConfig**, and **module**.
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| [app](app-structure.md) | Application-wide configuration. Different HAP files of an application must use the same **app** configuration. | Object| No|
| [deviceConfig](deviceconfig-structure.md) | Device-specific configuration. | Object| No|
| [module](module-structure.md) | HAP configuration. It is valid only for the current HAP file.| Object| No|
Example of the **config.json** file:
```json
{
"app": {
"vendor": "example",
"bundleName": "com.example.demo",
"version": {
"code": 1000000,
"name": "1.0.0"
}
},
"deviceConfig": {
},
"module": {
"mainAbility": ".MainAbility_entry",
"deviceType": [
"tablet"
],
"commonEvents": [
{
"name": ".MainAbility",
"permission": "ohos.permission.GET_BUNDLE_INFO",
"data": [
"com.example.demo",
"100"
],
"events": [
"install",
"update"
]
}
],
"abilities": [
{
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
],
"orientation": "unspecified",
"visible": true,
"srcPath": "MainAbility_entry",
"name": ".MainAbility_entry",
"srcLanguage": "ets",
"icon": "$media:icon",
// $string:MainAbility_entry_desc is a resource index.
"description": "$string:MainAbility_entry_desc",
"formsEnabled": false,
// $string:MainAbility_entry_label is a resource index.
"label": "$string:MainAbility_entry_label",
"type": "page",
"launchType": "standard"
}
],
"distro": {
"moduleType": "entry",
"installationFree": false,
"deliveryWithInstall": true,
"moduleName": "myapplication"
},
"package": "com.example.myapplication",
"srcPath": "",
"name": ".myapplication",
"js": [
{
"mode": {
"syntax": "ets",
"type": "pageAbility"
},
"pages": [
"pages/index"
],
"name": ".MainAbility_entry",
"window": {
"designWidth": 720,
"autoDesignWidth": false
}
}
]
}
}
```
# 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.
# Application Installation and Uninstallation Process
The OpenHarmony bundle manager service module provides APIs for installing, updating, and uninstalling applications. You can call these APIs when needed. After you release your application to the application market, users can install and uninstall it on their device.
**Figure 1** Process of installing and uninstalling an application
![hap-intall-uninstall](figures/hap-intall-uninstall.png)
# Application Package Overview
A user application, also known as an application or app, runs on the operating system of devices and provides particular services for users. The software package corresponding to an application is called an application package.
OpenHarmony provides an efficient management mechanism for application packages. By harnessing this mechanism, you can easily develop, install, query, update, and uninstall application packages.
- To accelerate application deployment, you can use the integrated development tool provided by OpenHarmony to integrate executable code, resources, and third-party libraries into an OpenHarmony application package.
- To distribute your application package by device type, you can specify the device types for distribution in the application package configuration file provided by OpenHarmony.
- An application may provide a wide range of features. It is a good practice to divide and manage application features by module. OpenHarmony provides a multi-package management mechanism on an application-by-application basis. You can aggregate different application features into different packages to facilitate subsequent maintenance and expansion.
- To allow an application to run across various chip platforms, such as x86, Arm, and other 32-bit or 64-bit platforms, OpenHarmony abstracts away the differences between chip platforms for application packages.
- With a myriad of query APIs in OpenHarmony, you can quickly check the information about applications, including the application versions, names, components, and permissions.
- To facilitate resource search and use, the bundle management service in OpenHarmony archives resources by type (media, native, string, internationalization, and more) in different directories and integrates resource index files.
# Application Package Structure in FA Model
To develop an application based on the [FA model](application-configuration-file-overview-fa.md), it is essential to understand the application package structure in this model.
The difference between the application package structures in the FA model and stage model lies in where the internal files of a HAP file are stored. In the FA model, all the resource files, library files, and code files are stored in the **assets** folder, where the files are further organized.
- **config.json** is an application configuration file, where the template code is automatically created by DevEco Studio. You can modify the configuration as required. For details about the fields in this file, see [Internal Structure of the app Tag](app-structure.md).
- The **assets** folder is a collection of all the resource files, library files, and code files in a HAP file. It can be further organized into the **entry** folder and the **js** folder. The **entry** folder stores the **resources** folder and the **resources.index** file.
- The **resources** folder stores resource files (such as strings and images) of the application.
- The **resources.index** file provides a resource index table, which is generated by DevEco Studio invoking the specific SDK tool.
- The **js** folder stores code files created after compilation.
- The **pack.info** file describes the HAP attributes in the bundle, for example, **bundleName** and **versionCode** in **app** and **name**, **type**, and **abilities** in **module**. The file is automatically generated when DevEco Studio generates the bundle.
**Figure 1** Application package structure in FA model
![app-pack-fa](figures/app-pack-fa.png)
\ No newline at end of file
# Application Package Structure in Stage Model
To develop an application based on the [stage model](application-configuration-file-overview-stage.md), it is essential to understand the structure of the application package created after the application is built and packaged.
- In development, an application contains one or more modules. You can [create modules](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3) in the application project in [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio/). As a basic functional unit of an OpenHarmony application/service, a module contains source code, resource files, third-party libraries, and application/service configuration files, and can be built and run independently. Modules can be classified as Ability or Library. A module of the Ability type is built into a Harmony Ability Package (HAP) file in .hap format, and a module of the Library type is built into a [Harmony Ability Resources (HAR) file](har-structure.md) in .tgz format.
A module can contain one or more [UIAbility](../application-models/uiability-overview.md) components, as shown in the figure below.
**Figure 1** Relationship between modules and UIAbility components
![ability-and-module](figures/ability-and-module.png)
Unless otherwise specified, the modules described in this document refer to the modules of the Ability type.
- As aforementioned, you can build an application into one or more HAP files. The HAP file is the basic unit for installing an application. It provides code, resources, third-party libraries, and a configuration file. HAP files can be classified as Entry or Feature.
- HAP of the entry type: main module of the application, whose **type** field is set to **"entry"** in the [module.json5](module-configuration-file.md) file. In an application, each type of device supports only one HAP of the entry type, which is typically used to implement the application's entry screen, entry icon, or headline feature.
- HAP of the feature type: dynamic feature module of the application, whose **type** field is set to **"feature"** in the [module.json5](module-configuration-file.md) file. Each application can contain zero, one, or more HAP files of the feature type, which are used to implement the application features. You can configure this type of HAP file to be downloaded and installed independently as required or to be downloaded and installed together with the HAP file of the entry type. For details, see **deliveryWithInstall** in [module.json5 Configuration File](module-configuration-file.md).
- All the HAP files in an application are integrated into a bundle, and the bundle name is the unique identifier of the application. For details, see **bundleName** tag in [app.json5 Configuration File](app-configuration-file.md). Note that to release an application to the application market, all HAP files (that is, the bundle) contained in the application must be packed into an Application Package (App Pack) in .app format, which also contains the **pack.info** file that describes the attributes of the App Pack. The App Pack is distributed and installed on the cloud and on the device on a HAP-by-HAP basis.
- The HAP file includes folders such as **ets**, **libs**, and **resources** and files such as **resources.index**, **module.json**, and **pack.info**.
- The **ets** folder stores bytecode files generated after application code build.
- The **libs** folder stores library files, which are .so binary files that contain third-party code on which the OpenHarmony application depends.
- The **resources** folder stores resource files (such as strings and images) of the application.
- The **resources.index** file provides a resource index table, which is generated when the application project is built in DevEco Studio.
- The **module.json** file is the configuration file indispensable in a HAP file. It consists of **module.json5** and **app.json5** in the project configuration. While DevEco Studio provides default configuration, you must modify the configuration as needed. For details about the configuration fields, see [Application Configuration Files in Stage Model](application-configuration-file-overview-stage.md).
- The **pack.info** file describes the HAP attributes in the bundle, for example, **bundleName** and **versionCode** in **app** and **name**, **type**, and **abilities** in **module**. The file is automatically generated when DevEco Studio generates the bundle.
**Figure 2** Application package structure in stage model
![app-pack-stage](figures/app-pack-stage.png)
\ No newline at end of file
......@@ -60,26 +60,15 @@ struct ComponentA {
this.label = (this.languageCode === 'en') ? 'Number' : 'Count'
})
}
.margin({ bottom: 50 })
.margin({ top: 50, bottom: 50 })
Row() {
Button (`Change @StorageLink decorated variable: ${this.varA}`).height(40).fontSize(14)
.onClick(() => {
this.varA++
})
}.margin({ bottom: 50 })
Row() {
Button (`Change @StorageProp decorated variable: ${this.languageCode}`).height(40).fontSize(14)
.onClick(() => {
if (this.languageCode === 'zh') {
this.languageCode = 'en'
} else {
this.languageCode = 'zh'
}
})
}
}
}.width('100%')
}
}
```
......@@ -110,27 +99,26 @@ One-way data binding can be established between a component and the **LocalStora
> **NOTE**
>
> If a **LocalStorage** instance has initial values assigned when being created, these values will be used for the **@LocalStorageLink** and **@LocalStorageProp** decorated state variables in the component. Otherwise, the initial values assigned for **@LocalStorageLink** and **@LocalStorageProp** will be used instead.
> If a **LocalStorage** instance does not have an initial value assigned when being created, it can use the initial value defined by **@LocalStorageLink** or **@LocalStorageProp** in the component.
### Example 1: Creating a LocalStorage Instance in an Ability
The **LocalStorage** is loaded through the **loadContent** API. For details, see [loadContent](../reference/apis/js-apis-window.md#loadcontent9-1).
```ts
// MainAbility.ts
import Ability from '@ohos.application.Ability'
import UIAbility from '@ohos.app.ability.UIAbility';
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
storage: LocalStorage
onCreate() {
this.storage = new LocalStorage()
this.storage.setOrCreate('storageSimpleProp', 121)
console.info('[Demo MainAbility onCreate]')
console.info('[Demo EntryAbility onCreate]')
}
onDestroy() {
console.info('[Demo MainAbility onDestroy]')
console.info('[Demo EntryAbility onDestroy]')
}
onWindowStageCreate(windowStage) {
......@@ -139,15 +127,15 @@ export default class MainAbility extends Ability {
}
onWindowStageDestroy() {
console.info('[Demo] MainAbility onWindowStageDestroy')
console.info('[Demo] EntryAbility onWindowStageDestroy')
}
onForeground() {
console.info('[Demo] MainAbility onForeground')
console.info('[Demo] EntryAbility onForeground')
}
onBackground() {
console.info('[Demo] MainAbility onBackground')
console.info('[Demo] EntryAbility onBackground')
}
}
```
......
......@@ -15,8 +15,8 @@ In the multi-dimensional state management mechanism for ArkUI, UI-related data c
| @Link | Primitive data types, classes, and arrays | This decorator is used to establish two-way data binding between the parent and child components. The internal state data of the parent component is used as the data source. Any changes made to one component will be reflected to the other.|
| @Observed | Class | This decorator is used to indicate that the data changes in the class will be managed by the UI page. |
| @ObjectLink | Objects of **@Observed** decorated classes| When the decorated state variable is modified, the parent and sibling components that have the state variable will be notified for UI re-rendering.|
| @Consume | Primitive data types, classes, and arrays | When the **@Consume** decorated variable detects the update of the **@Provide** decorated variable, the re-rendering of the current custom component is triggered.|
| @Provide | Primitive data types, classes, and arrays | As the data provider, **@Provide** can update the data of child nodes and trigger page re-rendering.|
| @Consume | Primitive data types, classes, and arrays | When the **@Consume** decorated variable detects the update of the **@Provide** decorated variable, the re-rendering of the current custom component is triggered.|
## State Management with Application-level Variables
......@@ -25,5 +25,8 @@ In the multi-dimensional state management mechanism for ArkUI, UI-related data c
- **@StorageLink**: works in a way similar to that of **@Consume**. The difference is that the target object is obtained from the **AppStorage** based on the given name. **@StorageLink** establishes two-way binding between the decorated UI component and **AppStorage** to synchronize data.
- **@StorageProp**: synchronizes UI component attributes with the **AppStorage** unidirectionally. That is, the value change in the **AppStorage** will trigger an update of the corresponding UI component, but the change of the UI component will not cause an update of the attribute value in the **AppStorage**.
- Service logic implementation API: adds, reads, modifies, or deletes the state data of applications. The changes made by this API will be synchronized to the UI component for UI update.
- **LocalStorage**: provides ability-specific storage.
- **@LocalStorageLink**: establishes two-way data binding between a component and the **LocalStorage**. Specifically, this is achieved by decorating the component's state variable with **@LocalStorageLink(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**.
- **@LocalStorageProp**: establishes one-way data binding between a component and the **LocalStorage**. Specifically, this is achieved by decorating the component's state variable with **@LocalStorageProp(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**.
- **PersistentStorage**: provides a set of static methods for managing persistent data of applications. Persistent data with specific tags can be linked to the **AppStorage**, and then the persistent data can be accessed through the **AppStorage** APIs. Alternatively, the **@StorageLink** decorator can be used to access the variable that matches the specific key.
- **Environment**: provides the **AppStorage** with an array of environment state attributes that are required by the application and describe the device environment where the application runs. It is a singleton object created by the framework when the application is started.
......@@ -82,18 +82,22 @@ struct MyComponent {
## @Prop
**@Prop** and **@State** have the same semantics but different initialization modes. Variables decorated by **@Prop** must be initialized using the **@State** decorated variable provided by their parent components. The **@Prop** decorated variable can be modified in the component, but the modification is not updated to the parent component; that is, **@Prop** uses one-way data binding.
**@Prop** and **@State** have the same semantics but different initialization modes. A **@Prop** decorated variable in a component must be initialized using the **@State** decorated variable in its parent component. The **@Prop** decorated variable can be modified in the component, but the modification is not updated to the parent component; the modification to the **@State** decorated variable is synchronized to the **@Prop** decorated variable. That is, **@Prop** establishes one-way data binding.
The **@Prop** decorated state variable has the following features:
- Support for simple types: The number, string, and boolean types are supported.
- Private: Data is accessed only within the component.
- Support for multiple instances: A component can have multiple attributes decorated by **@Prop**.
- Support for initialization with a value passed to the @Prop decorated variable: When a new instance of the component is created, all **@Prop** decorated variables must be initialized. Initialization inside the component is not supported.
- Support for initialization with a value passed to the @Prop decorated variable: When a new instance of the component is created, all **@Prop** variables must be initialized. Initialization inside the component is not supported.
> **NOTE**
>
> A **@Prop** decorated variable cannot be initialized inside the component.
**Example**
In the preceding example, when the user presses **+1** or **-1**, the status of the parent component changes and the **build** method is executed again. In this case, a new **CountDownComponent** instance is created. The **countDownStartValue** attribute of the parent component is used to initialize the **@Prop** decorated variable of the child component. When the **count - costOfOneAttempt** button of the child component is touched, the value of the **@Prop** decorated variable **count** is changed. As a result, the **CountDownComponent** is rendered again. However, the change of the **count** value does not affect the **countDownStartValue** value of the parent component.
In the following example, when the user presses **+1** or **-1**, the status of the parent component changes and the **build** method is executed again. In this case, a new **CountDownComponent** instance is created. The **countDownStartValue** attribute of the parent component is used to initialize the **@Prop** decorated variable of the child component. When the **count - costOfOneAttempt** button of the child component is touched, the value of the **@Prop** decorated variable **count** is changed. As a result, the **CountDownComponent** is rendered again. However, the change of the **count** value does not affect the **countDownStartValue** value of the parent component.
```ts
// xxx.ets
......@@ -152,13 +156,13 @@ Two-way binding can be established between the **@Link** decorated variable and
- Support for multiple types: The **@Link** decorated variables support the data types the same as the **@State** decorated variables; that is, the value can be of the following types: class, number, string, boolean, or arrays of these types.
- Private: Data is accessed only within the component.
- Single data source: The variable of the parent component used for initializing the **@Link** decorated variable must be a **@State** decorated variable.
- Single data source: The variable used to initialize the **@Link** decorated variable in a component must be a state variable defined in the parent component.
- **Two-way binding**: When a child component changes the **@Link** decorated variable, the **@State** decorated variable of its parent component is also changed.
- Support for initialization with the variable reference passed to the @Link decorated variable: When creating an instance of the component, you must use the naming parameter to initialize all **@Link** decorated variables. **@Link** decorated variables can be initialized by using the reference of the **@State** or **@Link** decorated variable. Wherein, the **@State** decorated variables can be referenced using the **'$'** operator.
> **NOTE**
>
> **@Link** decorated variables cannot be initialized within the component.
> A **@Link** decorated variable cannot be initialized inside the component.
**Simple Type Example**
......@@ -391,13 +395,13 @@ struct ViewB {
```
## @Consume and @Provide
## @Provide and @Consume
As the data provider, **@Provide** can update the data of child nodes and trigger page rendering. After **@Consume** detects that the **@Provide** decorated variable is updated, it will initiate re-rendering of the current custom component.
> **NOTE**
>
> To avoid infinite loops caused by circular reference, exercise caution when using **@Provide** and **@Consume**.
> When using **@Provide** and **@Consume**, avoid circular reference that may lead to infinite loops.
### @Provide
......
# Internal Structure of deviceConfig Tag
The **deviceConfig** tag contains device-specific configuration of the application, including attributes such as **default**, **tv**, **car**, and **wearable**. The **default** configuration applies to all types of devices. You need to declare the peculiar configuration of a specific device type in the associated sub-tag of this type.
### Table 1 Internal Structure of the deviceConfig Tag
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| default | Application configuration specific to the OpenHarmony device that provides full access to system capabilities.| Object| Yes (initial value: left empty)|
| tablet | Application configuration specific to tablets.| Object| Yes (initial value: left empty)|
| tv | Application configuration specific to smart TVs.| Object| Yes (initial value: left empty)|
| car | Application configuration specific to head units.| Object| Yes (initial value: left empty)|
| wearable | Application configuration specific to wearables.| Object| Yes (initial value: left empty)|
Table 2 describes the internal structure of the **deviceConfig** attributes.
#### Table 2 Internal Structure of the deviceConfig Attributes
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. The value can contain a maximum of 31 characters.| String| Yes (initial value: left empty)|
| keepAlive | Whether the application is always running. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the application will start during the OS startup and keep alive. If the application process exits, the OS will restart it.| Boolean| Yes (initial value: **false**)|
| supportBackup | Whether the application supports backup and restoration. The value **false** means that the application does not support backup or restoration.| Boolean| Yes (initial value: **false**)|
| compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.| Boolean| Yes (initial value: **false**)|
| network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code.| Object| Yes (initial value: left empty)|
#### Table 3 Internal Structure of the network Attribute
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| cleartextTraffic | Whether to allow the application to use plaintext traffic, for example, plaintext HTTP traffic.<br>**true**: The application is allowed to use plaintext traffic. **false**: The application is not allowed to use plaintext traffic.| Boolean| Yes (initial value: **false**)|
| securityConfig | Network security configuration of the application.| Object| Yes (initial value: left empty)|
#### Table 4 Internal Structure of the securityConfig Attribute
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| domainSettings | Security settings of the custom network domain. This attribute allows nested domains. That is, the **domainSettings** object of a network domain can be nested with the **domainSettings** objects of smaller network domains.| Object| Yes (initial value: left empty)|
#### Table 5 Internal Structure of the domainSettings Attribute
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| cleartextPermitted | Whether plaintext traffic can be transmitted in the custom network domain. If both **cleartextTraffic** and **security** are declared, whether plaintext traffic can be transmitted in the custom network domain is determined by the **cleartextPermitted** attribute. **true**: Plaintext traffic can be transmitted. **false**: Plaintext traffic cannot be transmitted.| Boolean| Yes (initial value: left empty)|
| domains | Domain name. This attribute consists of two sub-attributes: **subdomains** and **name**. **subdomains** (boolean): specifies whether the domain name contains subdomains. If this sub-attribute is set to **true**, the domain naming convention applies to all related domains and subdomains (including the lower-level domains of the subdomains). Otherwise, the convention applies only to exact matches. **name** (string): indicates the domain name.| Object array| Yes (initial value: left empty)|
### Example of the deviceConfig Tag
```json
"deviceConfig": {
"default": {
"process": "com.example.test.example",
"supportBackup": false,
"network": {
"cleartextTraffic": true,
"securityConfig": {
"domainSettings": {
"cleartextPermitted": true,
"domains": [
{
"subdomains": true,
"name": "example.ohos.com"
}
]
}
}
}
}
}
```
# HAR File Structure
The Harmony Ability Resources (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.
The HAR file reuses the standard [npm package](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434) release mode and is packed into a .tar package with the file name extension .tgz. The packed HAR file contains the source code, resource files, and the **module.json** file (in stage model) or **config.json** file (in FA model).
此差异已折叠。
# Multi-HAP Build View
DevEco Studio allows you to develop and build multiple HAP files in one application project, as shown below.
**Figure 1** Multi-HAP build view
![hap-multi-view](figures/hap-multi-view.png)
1. Development view in DevEco Studio
- AppScope folder
- [app.json5](app-configuration-file.md): application-wide configuration, such as the application bundle name, version number, application icon, application name, and dependent SDK version number.
- **resources** folder: stores application icon resources and application name string resources.
**NOTE**
- The folder is automatically generated by DevEco Studio and its name cannot be changed.
- The file names in the **AppScope** folder cannot be the same as those in the entry- or feature-type module directories. Otherwise, DevEco Studio reports an error.
- Entry- or feature-type module directories (the names are customizable)
- You implement service logic of your application in these module directories. In this example, the module folders are **entry.hap** and **feature.hap**.
- **resources** directory: stores the resources used by the module.
- **ets** folder: stores the service logic.
- [module.json5](module-configuration-file.md): module configuration, such as the module name, entry code path of the module, and component information.
2. View after build and packaging
- After a module is built, a HAP file for deployment is generated. Each module corresponds to a HAP file.
- The **module.json** file in the HAP file is composed of the **app.json5** and **module.json5** files in the development view.
- All HAP files are finally built into an Application Package (App Pack) in .app format for release to the application market.
# Multi-HAP Design Objectives
- Modular management: A well-designed application is generally managed in a modular manner, where modules are loosely coupled. In light of this, the multi-HAP mechanism is designed, allowing you to divide services into multiple modules and store each module in an independent HAP file. For example, If you are developing a payment application and its home screen consists of multiple modules, such as the scan, pay, messaging, and finance modules, you can implement the logic of the home screen for managing other modules in the entry-type HAP file, and implement specific modules in feature-type HAP files. The feature-type HAP files are independent. You can develop and test each of them separately, and then integrate them with the entry-type HAP file.
- Flexible deployment: You can combine multiple HAP files and deploy them on different devices. Assume that an application contains one entry-type HAP file (**Entry.hap**) and two feature-type HAP files (**Feature1.hap** and **Feature2.hap**). The **Entry.hap** file can be deployed on device A and device B, the **Feature1.hap** file can be deployed only on device A, and the **Feature2.hap** can be deployed only on device B. In this way, you can easily combine the **Entry.hap** and **Feature1.hap** files and deploy them on device A, and combine the **Entry.hap** and **Feature2.hap** files and deploy them on device B.
- On-demand loading: You can load modules only when they are needed, reducing the package size. Specifically, you can configure some HAP files of an application to be loaded on demand. For example, if some features are not used during application startup, you can configure them to be loaded only when they are needed, rather than being loaded at startup. This can reduce the size of the application package to some extent.
- Easier resource sharing: The resources (including public resource files and public pages) and shared objects (.so library files) required by multiple HAP files can be stored in an independent HAP file. In this way, other HAP files can obtain the resources and files by accessing the HAP, which reduces the size of the application package to some extent.
# Multi-HAP Operation Mechanism and Data Communication Modes
The multi-HAP mechanism is used to facilitate modular management for developers. There is no one-to-one mapping between the HAP and the running process of the application. The detailed running mechanism is as follows:
- By default, all UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components of an application (with the same bundle name) run in the same independent process, and other ExtensionAbility components of the same type run in separate processes.
- The HAP file supports the process configuration through the **process** tag in the **module.json5** (stage model) or **config.json** (FA model) file. This feature is supported only by system applications. If **process** is configured for an HAP file, all components of the HAP file run in an independent process. Multiple HAP files can be configured with the same process, in which case the HAP files run in the same process. For details about the process configuration, see [module.json5 Configuration File](module-configuration-file.md).
- When an application is running, the resources and code of the corresponding HAP file are loaded only when the UIAbility component in the same process is started.
Based on the preceding mechanism, the multi-HAP data communication modes are as follows:
- For details about data communication in the same process, see [Thread Model (Stage Model)](../application-models/thread-model-stage.md).
- For details about cross-process data communication, see [Process Model (Stage Model)](../application-models/process-model-stage.md).
- If multiple HAPs run in the same process, the communication mode between the components of multiple HAP files is the same as that between the components of the same HAP file.
# Multi-HAP Development, Debugging, Release, and Deployment Process
Below is the process of developing, debugging, releasing, and deploying multiple HAP files.
**Figure 1** Process of developing, debugging, releasing, and deploying multiple HAP files
![hap-release](figures/hap-release.png)
## Development
You can use [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio) to create multiple modules based on service requirements and develop services in independent modules.
## Debugging
You can use DevEco Studio to build code into one or more HAP files. Then, you can debug the HAP files.
* Using DevEco Studio for debugging
Follow the instructions in [Debugging Configuration](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-debugging-and-running-0000001263040487#section10491183521520).
* Using [hdc_std](../../device-dev/subsystems/subsys-toolchain-hdc-guide.md) for debugging
You can obtain the hdc_std tool from the **toolchains** directory of the SDK. When using this tool to install an HAP file, the HAP file path is the one on the operating platform. In this example, the Windows operating platform is used. The command reference is as follows:
```
// Installation and update: Multiple file paths can be specified.
hdc_std install C:\entry.hap C:\feature.hap
// The execution result is as follows:
install bundle successfully.
// Uninstall
hdc_std uninstall com.example.myapplication
// The execution result is as follows:
uninstall bundle successfully.
```
* Using Bundle Manager (bm) for debugging
When using bm to install or update an HAP file, the HAP file path is the one on the real device. The command reference is as follows:
```
// Installation and update: Multiple file paths can be specified.
bm install -p /data/app/entry.hap /data/app/ feature.hap
// The execution result is as follows:
install bundle successfully.
// Uninstall
bm uninstall -n com.example.myapplication
// The execution result is as follows:
uninstall bundle successfully.
```
## Release
When your application package meets the release requirements, you can package and build it into an App Pack and release it to the application market on the cloud. The application market verifies the signature of the App Pack. If the signature verification is successful, the application market obtains the HAP files from the App Pack, signs them, and distributes the signed HAP files.
## Deployment
The application market on the cloud distributes the applications to application market clients. These applications can contain one or more HAP files. After the user selects an application to download, the application market downloads all the HAP files contained in this application.
## Installation on a Device
After the download is complete, the application market client calls the installation API of the bundle manager service in the system to install the downloaded HAP files. The bundle manager service deploys HAP files by application in the specified directory to complete the application installation.
# Multi-HAP Usage Rules
- The App Pack cannot be directly installed on the device. It is only a unit that is released to AppGallery.
- All HAP files in the App Pack must share the same **bundleName** value in the configuration files.
- All HAP files in the App Pack must share the same **versionCode** value in the configuration files.
- In an application, each type of device supports only one HAP of the entry type. Each application can contain zero, one, or more HAP files of the feature type.
- Each HAP file in the App Pack must have **moduleName** configured. The **moduleName** value corresponding to all HAP files of the same device type must be unique.
- The signing certificates of all HAP files in the same application must be the same. Applications are released to the application market in the form of App Pack after being signed. Before distribution, the application market splits an App Pack into HAP files and resigns them to ensure the consistency of all HAP file signing certificates. Before installing HAP files on a device through the CLI or DevEco Studio for debugging, you must ensure that their signing certificates are the same. Otherwise, the installation will fail.
......@@ -4,7 +4,7 @@ This document is intended for novices at developing OpenHarmony applications. It
![en-us_image_0000001364254729](figures/en-us_image_0000001364254729.png)
Before you begin, there are two basic concepts that will help you better understand OpenHarmony: UI framework and ability.
Before you begin, there are two basic concepts that will help you better understand OpenHarmony: UI framework and application model.
## Basic Concepts
......@@ -16,29 +16,25 @@ OpenHarmony provides a UI development framework, known as ArkUI. ArkUI provides
ArkUI comes with two development paradigms: ArkTS-based declarative development paradigm (declarative development paradigm for short) and JavaScript-compatible web-like development paradigm (web-like development paradigm for short). You can choose whichever development paradigm that aligns with your practice.
| **Development Paradigm**| **Programming Language**| **UI Update Mode**| **Applicable To**| **Intended Audience**|
| -------- | -------- | -------- | -------- | -------- |
| Declarative development paradigm| ArkTS| Data-driven| Applications involving technological sophistication and teamwork| Mobile application and system application developers|
| Web-like development paradigm| JavaScript| Data-driven| Applications and service widgets with simple UIs| Frontend web developers|
| **Development Paradigm**| **Programming Language**| **UI Update Mode**| **Applicable To** | **Intended Audience** |
| ---------------- | ------------ | -------------- | -------------------------------- | -------------------------------------- |
| Declarative development paradigm | ArkTS | Data-driven | Applications involving technological sophistication and teamwork| Mobile application and system application developers|
| Web-like development paradigm | JavaScript | Data-driven | Applications and service widgets with simple UIs | Frontend web developers |
For more details, see [UI Development](../ui/arkui-overview.md).
### Application Model
### Ability
The application model is the abstraction of capabilities required by OpenHarmony applications. It provides necessary components and running mechanisms for applications. With application models, you can develop applications based on a unified set of models, making application development simpler and more efficient. For details, see [Elements of the Application Model](../application-models/application-model-composition.md).
An ability is the abstraction of a functionality that an application can provide. An application may provide various capabilities, and so it can have multiple abilities. These abilities can be deployed together or independently from each other.
Along its evolution, OpenHarmony has provided two application models:
The ability framework model has two forms:
- Feature Ability (FA) model. This model is supported by OpenHarmony API version 7 and 8. It is no longer recommended. For details about development based on the FA model, see [FA Model Development Overview](../application-models/fa-model-development-overview.md).
- Stage model. This model is supported since OpenHarmony API version 9. It is recommended and will evolve for a long time. In this model, classes such as **AbilityStage** and **WindowStage** are provided as the stage of application components and windows. That's why it is named stage model. For details about development based on the stage model, see [Stage Model Development Overview](../application-models/fa-model-development-overview.md).
- **FA model**: applies to application development using API version 8 and earlier versions. For details, see [FA Model Overview](../ability/fa-brief.md).
For details about the differences between the FA model and stage model, see [Interpretation of the Application Model](../application-models/application-model-description.md).
- **Stage model**: introduced since API version 9. For details, see [Stage Model Overview](../ability/stage-brief.md).
The project directory structure of the FA model is different from that of the stage model. The stage model only works with the ArkTS programming language.
For details about the differences between the FA model and stage model, see [Ability Framework Overview](../ability/ability-brief.md).
This document provides an ability with two pages. For more information about ability development, see [Ability Development](../ability/ability-brief.md).
To help you better understand the preceding basic concepts and application development process, **Getting Started** provides a development example that contains two pages in different programming languages and application models.
## Tool Preparation
......
......@@ -40,7 +40,7 @@
- **src > main > ets > MainAbility > pages > index.ets**: the first page in the **pages** list, also referred to as the entry to the application.
- **src > main > ets > MainAbility > app.ets**: ability lifecycle file.
- **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Categories and Access](resource-categories-and-access.md#resource-categories).
- **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details about the configuration file, see [Application Package Structure Configuration File (FA Model)](package-structure.md).
- **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details, see [Application Configuration File Overview (FA Model)](application-configuration-file-overview-fa.md).
- **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**.
- **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation.
......@@ -129,7 +129,7 @@
> **NOTE**
>
> You can also right-click the **pages** folder and choose **New** > **Page** from the shortcut menu. In this scenario, you do not need to manually configure page routes.
- Configure the route for the second page, by setting **pages/second** under **module - js - pages** in the **config.json** The sample code is as follows: The sample code is as follows:
- Configure the route for the second page, by setting **pages/second** under **module - js - pages** in the **config.json** file. The sample code is as follows:
```json
{
......@@ -223,7 +223,7 @@ You can implement page redirection through the [page router](../reference/apis/j
.height('5%')
// Bind the onClick event to the Next button so that clicking the button redirects the user to the second page.
.onClick(() => {
router.push({ url: 'pages/second' })
router.pushUrl({ url: 'pages/second' })
})
}
.width('100%')
......
......@@ -38,7 +38,7 @@
- **src > main > ets > entryability**: entry to your application/service.
- **src > main > ets > pages**: pages included in your application/service.
- **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Categories and Access](resource-categories-and-access.md#resource-categories).
- **src > main > module.json5**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details about the configuration file, see [Application Package Structure Configuration File (Stage Model)](stage-structure.md).
- **src > main > module.json5**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details, see [module.json5 Configuration File](module-configuration-file.md).
- **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**.
- **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation.
......@@ -216,7 +216,7 @@ You can implement page redirection through the [page router](../reference/apis/j
.height('5%')
// Bind the onClick event to the Next button so that clicking the button redirects the user to the second page.
.onClick(() => {
router.push({ url: 'pages/Second' })
router.pushUrl({ url: 'pages/Second' })
})
}
.width('100%')
......
......@@ -39,7 +39,7 @@
- **src > main > js > MainAbility > app.js**: ability lifecycle file.
- **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Limitations and Access](../ui/js-framework-resource-restriction.md).
- **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details about the configuration file, see [Application Package Structure Configuration File (FA Model)](package-structure.md).
- **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details, see [Application Configuration File Overview (FA Model)](application-configuration-file-overview-fa.md).
- **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**.
- **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation.
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册