You need to sign in or sign up before continuing.
提交 650c84b3 编写于 作者: G Gloria

Update docs against 16982+16904+16903+16912+16809+16724+16802

Signed-off-by: wusongqing<wusongqing@huawei.com>
上级 473e9bbd
...@@ -18,7 +18,6 @@ ...@@ -18,7 +18,6 @@
- [ExtensionAbility Component Overview](extensionability-overview.md) - [ExtensionAbility Component Overview](extensionability-overview.md)
- [ServiceExtensionAbility](serviceextensionability.md) - [ServiceExtensionAbility](serviceextensionability.md)
- [DataShareExtensionAbility (for System Applications Only)](datashareextensionability.md) - [DataShareExtensionAbility (for System Applications Only)](datashareextensionability.md)
- [FormExtensionAbility (Widget)](widget-development-stage.md)
- [AccessibilityExtensionAbility](accessibilityextensionability.md) - [AccessibilityExtensionAbility](accessibilityextensionability.md)
- [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md) - [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md)
- [InputMethodExtensionAbility](inputmethodextentionability.md) - [InputMethodExtensionAbility](inputmethodextentionability.md)
......
# Using Explicit Want to Start an Ability # Using Explicit Want to Start an Ability
When a user touches a button in an application, the application often needs to start a UIAbility component to complete a specific task. If the **abilityName** and **bundleName** parameters are specified when starting a UIAbility, then the explicit Want is used. Using Explicit Want
When a user touches a button in an application, the application often needs to start a UIAbility component to complete a specific task. The following describes how to use explicit Want to start a UIAbility component in an application. The user touches a button in the application to start the UIAbility component to complete a specific task. To start the UIAbility component in explicit Want mode, the **abilityName** and **bundleName** parameters must be specified. For details, see [Starting UIAbility in the Same Application](uiability-intra-device-interaction.md#starting-uiability-in-the-same-application).
## How to Develop
1. In a project of the stage model, create an ability and a page, named **callerAbility** and **Index.ets**, respectively. Use the **windowStage.loadContent()** method in the **onWindowStageCreate** function in the **callerAbility.ts** file to bind the two.
```ts
// ...
// callerAbility.ts
onWindowStageCreate(windowStage) {
// Main window is created, set main page for this ability
console.info('[Demo] EntryAbility onWindowStageCreate')
// Bind callerAbility with a paged named Index
windowStage.loadContent('pages/Index')
}
// ...
```
2. Repeat the preceding operation to create another ability named **calleeAbility**.
3. Add a button to the **Index.ets** page of **callerAbility**.
```ts
// ...
build() {
Row() {
Column() {
Text('hello')
.fontSize(50)
.fontWeight(FontWeight.Bold)
// A new button with will call explicitStartAbility() when clicked.
Button("CLICKME")
.onClick(this.explicitStartAbility) // For details about explicitStartAbility, see the sample code below.
// ...
}
.width('100%')
}
.height('100%')
}
// ...
```
4. Override the **onClick** method and use explicit Want to start **calleeAbility** in the method. The **bundleName** field can be obtained from the **AppScope > app.json5** file of the project. The **abilityName** field can be obtained from the **yourModuleName &gt; src &gt; main &gt; module.json5** file of the corresponding module.
```ts
import common from '@ohos.app.ability.common';
// ...
async explicitStartAbility() {
try {
// Explicit want with abilityName specified.
let want = {
deviceId: "",
bundleName: "com.example.myapplication",
abilityName: "calleeAbility"
};
let context = getContext(this) as common.UIAbilityContext;
await context.startAbility(want);
console.info(`explicit start ability succeed`);
} catch (error) {
console.info(`explicit start ability failed with ${error.code}`);
}
}
// ...
```
5. When you touch **CLICKME**, the corresponding page is displayed.
<img src="figures/startAbilityWtExplicitWant.PNG" alt="startAbilityWtExplicitWant" style="zoom: 80%;" />
# Using Implicit Want to Open a Website # Using Implicit Want to Open a Website
This section uses the operation of using a browser to open a website as an example. It is assumed that one or more browser applications are installed on the device. To ensure that the browser application can work properly, configure the [module.json5 file](../quick-start/module-configuration-file.md) as follows:
## Prerequisites
One or more browsers are installed on your device.
The **module.json5** of a browser application is as follows:
```json ```json
"skills": [ {
{ "module": {
"entities": [ // ...
"entity.system.browsable" "abilities": [
// ...
],
"actions": [
"ohos.want.action.viewData"
// ...
],
"uris": [
{
"scheme": "https",
"host": "www.test.com",
"port": "8080",
// Prefix matching is used.
"pathStartWith": "query",
"type": "text/*"
},
{ {
"scheme": "http",
// ... // ...
"skills": [
{
"entities": [
"entity.system.home",
"entity.system.browsable"
// ...
],
"actions": [
"action.system.home",
"ohos.want.action.viewData"
// ...
],
"uris": [
{
"scheme": "https",
"host": "www.test.com",
"port": "8080",
// Prefix matching is used.
"pathStartWith": "query"
},
{
"scheme": "http",
// ...
}
// ...
]
}
]
} }
// ...
] ]
}, }
] }
``` ```
In the initiator UIAbility, use implicit Want to start the browser application.
## How to Develop ```ts
import common from '@ohos.app.ability.common';
1. Use the custom function **implicitStartAbility** to start an ability. function implicitStartAbility() {
let context = getContext(this) as common.UIAbilityContext;
```ts let wantInfo = {
async implicitStartAbility() { // Uncomment the line below if you want to implicitly query data only in the specific bundle.
try { // bundleName: 'com.example.myapplication',
let want = { 'action': 'ohos.want.action.viewData',
// Uncomment the line below if you want to implicitly query data only in the specific bundle. // entities can be omitted.
// bundleName: "com.example.myapplication", 'entities': ['entity.system.browsable'],
"action": "ohos.want.action.viewData", 'uri': 'https://www.test.com:8080/query/student'
// entities can be omitted. }
"entities": [ "entity.system.browsable" ], context.startAbility(wantInfo).then(() => {
"uri": "https://www.test.com:8080/query/student", // ...
"type": "text/plain" }).catch((err) => {
} // ...
let context = getContext(this) as common.UIAbilityContext; })
await context.startAbility(want) }
console.info(`explicit start ability succeed`) ```
} catch (error) {
console.info(`explicit start ability failed with ${error.code}`)
}
}
```
The matching process is as follows:
1. If **action** in the passed **want** parameter is specified and is included in **actions** under **skills**, the matching is successful.
2. If **entities** in the passed **want** parameter is specified and is included in **entities** under **skills**, the matching is successful.
3. If **uri** in the passed **want** parameter is included in **uris** under **skills**, which is concatenated into `https://www.test.com:8080/query*` (where \* is a wildcard), the matching is successful. The matching process is as follows:
4. If **type** in the passed **want** parameter is specified and is included in **type** under **skills**, the matching is successful. 1. If **action** in the passed **want** parameter is specified and is included in **actions** under **skills** of the ability to match, the matching is successful.
2. If **entities** in the passed **want** parameter is specified and is included in **entities** under **skills** of the ability to match, the matching is successful.
3. If **uri** in the passed **want** parameter is included in **uris** under **skills** of the ability to match, which is concatenated into https://www.test.com:8080/query* (where * is a wildcard), the matching is successful.
4. If **type** in the passed **want** parameter is specified and is included in **type** under **skills** of the ability to match, the matching is successful.
2. When there are multiple matching applications, a dialog box is displayed for you to select one of them. If there are multiple matching applications, the system displays a dialog box for you to select one of them. The following figure shows an example.
![stage-want1](figures/stage-want1.png) ![stage-want1](figures/stage-want1.png)
...@@ -6,56 +6,60 @@ ...@@ -6,56 +6,60 @@
[Context](../reference/apis/js-apis-inner-application-context.md) is the context of an object in an application. It provides basic information about the application, for example, **resourceManager**, **applicationInfo**, **dir** (application development path), and **area** (encrypted area). It also provides basic methods such as **createBundleContext()** and **getApplicationContext()**. The UIAbility component and ExtensionAbility derived class components have their own **Context** classes, for example, the base class **Context**, **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, **ExtensionContext**, and **ServiceExtensionContext**. [Context](../reference/apis/js-apis-inner-application-context.md) is the context of an object in an application. It provides basic information about the application, for example, **resourceManager**, **applicationInfo**, **dir** (application development path), and **area** (encrypted area). It also provides basic methods such as **createBundleContext()** and **getApplicationContext()**. The UIAbility component and ExtensionAbility derived class components have their own **Context** classes, for example, the base class **Context**, **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, **ExtensionContext**, and **ServiceExtensionContext**.
- The figure below illustrates the inheritance relationship of contexts. - The figure below illustrates the inheritance relationship of contexts.
![context-inheritance](figures/context-inheritance.png) ![context-inheritance](figures/context-inheritance.png)
- The figure below illustrates the holding relationship of contexts. - The figure below illustrates the holding relationship of contexts.
![context-holding](figures/context-holding.png) ![context-holding](figures/context-holding.png)
- The following describes the information provided by different contexts. - 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, and more. - [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md): Each UIAbility has the **Context** attribute, which provides APIs to operate an application component, obtain the application component configuration, and more.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
let uiAbilityContext = this.context; let uiAbilityContext = this.context;
// ... // ...
} }
} }
``` ```
> **NOTE**
>
> For details about how to obtain the context of a **UIAbility** instance on the page, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
- Scenario-specific [ExtensionContext](../reference/apis/js-apis-inner-application-extensionContext.md): For example, ServiceExtensionContext, inherited from ExtensionContext, provides APIs related to background services. - Scenario-specific [ExtensionContext](../reference/apis/js-apis-inner-application-extensionContext.md): For example, ServiceExtensionContext, inherited from ExtensionContext, provides APIs related to background services.
```ts ```ts
import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility';
export default class MyService extends ServiceExtensionAbility { export default class MyService extends ServiceExtensionAbility {
onCreate(want) { onCreate(want) {
let serviceExtensionContext = this.context; let serviceExtensionContext = this.context;
// ... // ...
} }
} }
``` ```
- [AbilityStageContext](../reference/apis/js-apis-inner-application-abilityStageContext.md): module-level context. It provides **HapModuleInfo** and **Configuration** in addition to those provided by the base class **Context**. - [AbilityStageContext](../reference/apis/js-apis-inner-application-abilityStageContext.md): module-level context. It provides **HapModuleInfo** and **Configuration** in addition to those provided by the base class **Context**.
```ts ```ts
import AbilityStage from "@ohos.app.ability.AbilityStage"; import AbilityStage from '@ohos.app.ability.AbilityStage';
export default class MyAbilityStage extends AbilityStage { export default class MyAbilityStage extends AbilityStage {
onCreate() { onCreate() {
let abilityStageContext = this.context; let abilityStageContext = this.context;
// ... // ...
} }
} }
``` ```
- [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md): application-level context. It provides APIs for subscribing to ability lifecycle changes, system memory changes, and system environment changes. The application-level context can be obtained from UIAbility, ExtensionAbility, and AbilityStage. - [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md): application-level context. It provides APIs for subscribing to application component lifecycle changes, system memory changes, and system environment changes. The application-level context can be obtained from UIAbility, ExtensionAbility, and AbilityStage.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
let applicationContext = this.context.getApplicationContext(); let applicationContext = this.context.getApplicationContext();
// ... // ...
} }
} }
``` ```
...@@ -67,9 +71,9 @@ This topic describes how to use the context in the following scenarios: ...@@ -67,9 +71,9 @@ This topic describes how to use the context in the following scenarios:
- [Obtaining the Application Development Path](#obtaining-the-application-development-path) - [Obtaining the Application Development Path](#obtaining-the-application-development-path)
- [Obtaining and Modifying Encrypted Areas](#obtaining-and-modifying-encrypted-areas) - [Obtaining and Modifying Encryption Areas](#obtaining-and-modifying-encryption-areas)
- [Creating Context of Another Application or Module](#creating-context-of-another-application-or-module) - [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) - [Subscribing to UIAbility Lifecycle Changes in a Process](#subscribing-to-uiability-lifecycle-changes-in-a-process)
### Obtaining the Application Development Path ### Obtaining the Application Development Path
...@@ -80,13 +84,13 @@ The following table describes the application development paths obtained from co ...@@ -80,13 +84,13 @@ The following table describes the application development paths obtained from co
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| cacheDir | string | Yes| No| Cache directory of the application on the internal storage.<br>It is the content of **Storage** of an application under **Settings > Apps & services > Apps**.| | bundleCodeDir | string | Yes | No | Path for storing the application's installation package, that is, installation directory of the application on the internal storage. |
| tempDir | string | Yes| No| Temporary file directory of the application.<br>Files in this directory are deleted after the application is uninstalled.| | cacheDir | string | Yes| No| Path for storing the application's cache files, that is, cache directory of the application on the internal storage.<br>It is the content of **Storage** of an application under **Settings > Apps & services > Apps**.|
| filesDir | string | Yes| No| File directory of the application on the internal storage.<br>Files in this directory may be synchronized to other directories during application migration or backup.| | filesDir | string | Yes | No | Path for storing the application's common files, that is, file directory of the application on the internal storage.<br>Files in this directory may be synchronized to other directories during application migration or backup.|
| databaseDir | string | Yes| No| Storage directory of the local database.| | preferencesDir | string | Yes | Yes | Path for storing the application's preference files, that is, preferences directory of the application. |
| bundleCodeDir | string | Yes| No| Installation directory of the application on the internal storage. A resource file cannot be accessed by combining paths. Use [Resource Manager](../reference/apis/js-apis-resource-manager.md) to access it. | | tempDir | string | Yes | No | Path for storing the application's temporary files.<br>Files in this directory are deleted after the application is uninstalled.|
| distributedFilesDir | string | Yes| No| Storage directory of distributed application data files.| | databaseDir | string | Yes | No | Path for storing the application's database, that is, storage directory of the local database. |
| preferencesDir | string | Yes| Yes| Preferences directory of the application.| | distributedFilesDir | string | Yes| No| Path for storing the application's distributed files.|
The capability of obtaining the application development path is provided by the base class **Context**. This capability is also provided by **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext**. However, the paths obtained from different contexts may differ, as shown below. The capability of obtaining the application development path is provided by the base class **Context**. This capability is also provided by **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext**. However, the paths obtained from different contexts may differ, as shown below.
...@@ -111,7 +115,7 @@ The capability of obtaining the application development path is provided by the ...@@ -111,7 +115,7 @@ The capability of obtaining the application development path is provided by the
| bundleCodeDir | {Path prefix}/el1/bundle/| | bundleCodeDir | {Path prefix}/el1/bundle/|
| cacheDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/cache/| | cacheDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/cache/|
| filesDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/files/| | filesDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/files/|
| preferencesDir | {path prefix}/{encryption level}/base/**haps/{moduleName}**/preferences/| | preferencesDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/preferences/|
| tempDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/temp/| | tempDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/temp/|
| databaseDir | {Path prefix}/{Encryption level}/database/**{moduleName}**/| | databaseDir | {Path prefix}/{Encryption level}/database/**{moduleName}**/|
| distributedFilesDir | {Path prefix}/el2/distributedFiles/**{moduleName}**/| | distributedFilesDir | {Path prefix}/el2/distributedFiles/**{moduleName}**/|
...@@ -123,83 +127,92 @@ The sample code for obtaining the application development paths is as follows: ...@@ -123,83 +127,92 @@ The sample code for obtaining the application development paths is as follows:
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
let cacheDir = this.context.cacheDir; let cacheDir = this.context.cacheDir;
let tempDir = this.context.tempDir; let tempDir = this.context.tempDir;
let filesDir = this.context.filesDir; let filesDir = this.context.filesDir;
let databaseDir = this.context.databaseDir; let databaseDir = this.context.databaseDir;
let bundleCodeDir = this.context.bundleCodeDir; let bundleCodeDir = this.context.bundleCodeDir;
let distributedFilesDir = this.context.distributedFilesDir; let distributedFilesDir = this.context.distributedFilesDir;
let preferencesDir = this.context.preferencesDir; let preferencesDir = this.context.preferencesDir;
// ... // ...
} }
} }
``` ```
> **NOTE**
>
> The sample code obtains the sandbox path of the application development path. The absolute path can be obtained by running the **find / -name <fileName>** command in the hdc shell after file creation or modification.
### Obtaining and Modifying Encrypted Areas ### Obtaining and Modifying Encryption Areas
You can read and write [the area attribute in the context](../reference/apis/js-apis-inner-application-context.md) to obtain and set an encrypted area. Two encryption levels are supported: Encrypting application files enhances data security by preventing files from unauthorized access. Different application files require different levels of protection. For private files, such as alarms and wallpapers, the application must place them in the device-level encryption area (EL1) to ensure that they can be accessed before the user enters the password. For sensitive files, such as personal privacy data, the application must place them in the user-level encryption area (EL2).
- AreaMode.EL1: device-level encryption area, which is accessible after the device is powered on. In practice, you need to select a proper encrypted area based on scenario-specific requirements to protect application data security. The proper use of EL1 and the EL2 can efficiently improve the security.
- AreaMode.EL2: user-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time). > **NOTE**
>
> - AreaMode.EL1: device-level encryption area, which is accessible after the device is powered on.
>
> - AreaMode.EL2: user-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).
You can obtain and set the encryption area by reading and writing the [area attribute in Context](../reference/apis/js-apis-inner-application-context.md).
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
// Before storing common information, switch the encryption level to EL1. // Before storing common information, switch the encryption level to EL1.
if (this.context.area === 1) {// Obtain the area. if (this.context.area === 1) {// Obtain the area.
this.context.area = 0; // Modify the area. this.context.area = 0; // Modify the area.
}
// Store common information.
// Before storing sensitive information, switch the encryption level to EL2.
if (this.context.area === 0) { // Obtain the area.
this.context.area = 1; // Modify the area.
}
// Store sensitive information.
} }
// Store common information.
// Before storing sensitive information, switch the encryption level to EL2.
if (this.context.area === 0) { // Obtain the area.
this.context.area = 1; // Modify the area.
}
// Store sensitive information.
}
} }
``` ```
### Creating Context of Another Application or Module ### Creating Context of Another Application or Module
The base class **Context** provides the [createBundleContext(bundleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatebundlecontext), [createModuleContext(moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext), and [createModuleContext(bundleName:string, moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext-1) methods for creating the context of other applications or modules, so as to obtain the resource information, for example, [obtaining the application development paths](#obtaining-the-application-development-path) of other modules. The base class **Context** provides [createBundleContext(bundleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatebundlecontext), [createModuleContext(moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext), and [createModuleContext(bundleName:string, moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext-1) to create the context of other applications or modules, so as to obtain the resource information, for example, [obtaining the application development paths](#obtaining-the-application-development-path) of other modules.
- Call **createBundleContext(bundleName:string)** to create the context of another application. - Call **createBundleContext(bundleName:string)** to create the context of another application.
> **NOTE** > **NOTE**
> >
> To obtain the context of another application: > To obtain the context of another application:
> >
> - 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). > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
> >
> - This is a system API and cannot be called by third-party applications. > - 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. 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 ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
let bundleName2 = "com.example.application"; let bundleName2 = 'com.example.application';
let context2 = this.context.createBundleContext(bundleName2); let context2 = this.context.createBundleContext(bundleName2);
let label2 = context2.applicationInfo.label; let label2 = context2.applicationInfo.label;
// ... // ...
} }
} }
``` ```
- 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. - 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** > **NOTE**
> >
> To obtain the context of a specified module of another application: > To obtain the context of a specified module of another application:
> >
> - 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). > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
> >
> - This is a system API and cannot be called by third-party applications. > - This is a system API and cannot be called by third-party applications.
...@@ -207,12 +220,12 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -207,12 +220,12 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
let bundleName2 = "com.example.application"; let bundleName2 = 'com.example.application';
let moduleName2 = "module1"; let moduleName2 = 'module1';
let context2 = this.context.createModuleContext(bundleName2, moduleName2); let context2 = this.context.createModuleContext(bundleName2, moduleName2);
// ... // ...
} }
} }
``` ```
...@@ -222,77 +235,90 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -222,77 +235,90 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
let moduleName2 = "module1"; let moduleName2 = 'module1';
let context2 = this.context.createModuleContext(moduleName2); let context2 = this.context.createModuleContext(moduleName2);
// ... // ...
} }
} }
``` ```
### Subscribing to Ability Lifecycle Changes in a Process ### Subscribing to UIAbility Lifecycle Changes in a Process
In the DFX statistics scenario of an application, if you need to collect statistics on the stay duration and access frequency of a page, you can subscribe to ability lifecycle changes. In the DFX statistics scenario of an application, if you need to collect statistics on the stay duration and access frequency of a page, you can subscribe to UIAbility lifecycle changes in a process.
When the ability lifecycle changes in a process, for example, being created or destroyed, becoming visible or invisible, or gaining or losing focus, the corresponding callback is triggered, and a listener ID is returned. The ID is incremented by 1 each time the listener is registered. When the number of listeners exceeds the upper limit (2^63-1), -1 is returned. The following uses [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) as an example. [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext) provides APIs for subscribing to UIAbility lifecycle changes in a process. When the UIAbility lifecycle changes in a process, for example, being created or destroyed, becoming visible or invisible, or gaining or losing focus, the corresponding callback is triggered. Each time the callback is registered, a listener lifecycle ID is returned, with the value incremented by 1 each time. When the number of listeners exceeds the upper limit (2^63-1), **-1** is returned. The following uses [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) as an example.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window'; import window from '@ohos.window';
const TAG: string = "[Example].[Entry].[EntryAbility]"; const TAG: string = '[Example].[Entry].[EntryAbility]';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
lifecycleId: number; // Define a lifecycle ID.
lifecycleId: number;
onCreate(want, launchParam) {
let abilityLifecycleCallback = { onCreate(want, launchParam) {
onAbilityCreate(ability) { // Define a lifecycle callback object.
console.info(TAG, "onAbilityCreate ability:" + JSON.stringify(ability)); let abilityLifecycleCallback = {
}, // Called when a UIAbility is created.
onWindowStageCreate(ability, windowStage) { onAbilityCreate(uiAbility) {
console.info(TAG, "onWindowStageCreate ability:" + JSON.stringify(ability)); console.log(TAG, `onAbilityCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
console.info(TAG, "onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); },
}, // Called when a window is created.
onWindowStageActive(ability, windowStage) { onWindowStageCreate(uiAbility, windowStage: window.WindowStage) {
console.info(TAG, "onWindowStageActive ability:" + JSON.stringify(ability)); console.log(TAG, `onWindowStageCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
console.info(TAG, "onWindowStageActive windowStage:" + JSON.stringify(windowStage)); console.log(TAG, `onWindowStageCreate windowStage: ${JSON.stringify(windowStage)}`);
}, },
onWindowStageInactive(ability, windowStage) { // Called when the window becomes active.
console.info(TAG, "onWindowStageInactive ability:" + JSON.stringify(ability)); onWindowStageActive(uiAbility, windowStage: window.WindowStage) {
console.info(TAG, "onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); console.log(TAG, `onWindowStageActive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
}, console.log(TAG, `onWindowStageActive windowStage: ${JSON.stringify(windowStage)}`);
onWindowStageDestroy(ability, windowStage) { },
console.info(TAG, "onWindowStageDestroy ability:" + JSON.stringify(ability)); // Called when the window becomes inactive.
console.info(TAG, "onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); onWindowStageInactive(uiAbility, windowStage: window.WindowStage) {
}, console.log(TAG, `onWindowStageInactive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
onAbilityDestroy(ability) { console.log(TAG, `onWindowStageInactive windowStage: ${JSON.stringify(windowStage)}`);
console.info(TAG, "onAbilityDestroy ability:" + JSON.stringify(ability)); },
}, // Called when the window is destroyed.
onAbilityForeground(ability) { onWindowStageDestroy(uiAbility, windowStage: window.WindowStage) {
console.info(TAG, "onAbilityForeground ability:" + JSON.stringify(ability)); console.log(TAG, `onWindowStageDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
}, console.log(TAG, `onWindowStageDestroy windowStage: ${JSON.stringify(windowStage)}`);
onAbilityBackground(ability) { },
console.info(TAG, "onAbilityBackground ability:" + JSON.stringify(ability)); // Called when the UIAbility is destroyed.
}, onAbilityDestroy(uiAbility) {
onAbilityContinue(ability) { console.log(TAG, `onAbilityDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
console.info(TAG, "onAbilityContinue ability:" + JSON.stringify(ability)); },
} // Called when the UIAbility is switched from the background to the foreground.
} onAbilityForeground(uiAbility) {
// 1. Obtain the application context through the context attribute. console.log(TAG, `onAbilityForeground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
let applicationContext = this.context.getApplicationContext(); },
// 2. Register a listener for the lifecycle changes through the application context. // Called when the UIAbility is switched from the foreground to the background.
this.lifecycleId = applicationContext.on("abilityLifecycle", abilityLifecycleCallback); onAbilityBackground(uiAbility) {
console.info(TAG, "register callback number: " + JSON.stringify(this.lifecycleId)); console.log(TAG, `onAbilityBackground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
},
// Called when UIAbility is continued on another device.
onAbilityContinue(uiAbility) {
console.log(TAG, `onAbilityContinue uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
}
} }
// Obtain the application context.
let applicationContext = this.context.getApplicationContext();
// Register the application lifecycle callback.
this.lifecycleId = applicationContext.on('Lifecycle', abilityLifecycleCallback);
console.log(TAG, `register callback number: ${this.lifecycleId}`);
}
onDestroy() { // ...
let applicationContext = this.context.getApplicationContext();
applicationContext.off("abilityLifecycle", this.lifecycleId, (error, data) => { onDestroy() {
console.info(TAG, "unregister callback success, err: " + JSON.stringify(error)); // Obtain the application context.
}); let applicationContext = this.context.getApplicationContext();
} // Deregister the application lifecycle callback.
applicationContext.off('abilityLifecycle', this.lifecycleId);
}
} }
``` ```
...@@ -30,7 +30,7 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol ...@@ -30,7 +30,7 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol
- An application is considered as a foreground application only when the application process gains focus or its UIAbility component is running in the foreground. - An application is considered as a foreground application only when the application process gains focus or its UIAbility component is running in the foreground.
- Verify the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - Verify the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
- **When the startAbilityByCall() method is used, verify the call permission.** For details, see [Using Ability Call to Implement UIAbility Interaction](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction) and [Using Cross-Device Ability Call](hop-multi-device-collaboration.md#using-cross-device-ability-call). - **When the startAbilityByCall() method is used, verify the call permission.** For details, see [Using Call to Implement UIAbility Interaction](uiability-intra-device-interaction.md#using-call-to-implement-uiability-interaction) and [Using Cross-Device Call](hop-multi-device-collaboration.md#using-cross-device-call).
- Verify the **ohos.permission.ABILITY_BACKGROUND_COMMUNICATION** permission. - Verify the **ohos.permission.ABILITY_BACKGROUND_COMMUNICATION** permission.
......
...@@ -30,7 +30,7 @@ export default { ...@@ -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 EntryAbility: 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:
```json ```json
{ {
...@@ -48,13 +48,13 @@ After the PageAbility is created, its abilities-related configuration items are ...@@ -48,13 +48,13 @@ After the PageAbility is created, its abilities-related configuration items are
], ],
"orientation": "unspecified", "orientation": "unspecified",
"visible": true, "visible": true,
"srcPath": "EntryAbility", "srcPath": "MainAbility",
"name": ".EntryAbility", "name": ".MainAbility",
"srcLanguage": "ets", "srcLanguage": "ets",
"icon": "$media:icon", "icon": "$media:icon",
"description": "$string:EntryAbility_desc", "description": "$string:MainAbility_desc",
"formsEnabled": false, "formsEnabled": false,
"label": "$string:EntryAbility_label", "label": "$string:MainAbility_label",
"type": "page", "type": "page",
"launchType": "singleton" "launchType": "singleton"
} }
...@@ -76,22 +76,22 @@ In the FA model, you can call **getContext** of **featureAbility** to obtain the ...@@ -76,22 +76,22 @@ In the FA model, you can call **getContext** of **featureAbility** to obtain the
The following code snippet shows how to use **getContext()** to obtain the application context and distributed directory: The following code snippet shows how to use **getContext()** to obtain the application context and distributed directory:
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility';
import fileIo from '@ohos.fileio' import fs from '@ohos.file.fs';
(async () => { (async () => {
let dir: string let dir: string;
try { try {
console.info('Begin to getOrCreateDistributedDir') console.info('Begin to getOrCreateDistributedDir');
dir = await featureAbility.getContext().getOrCreateDistributedDir() dir = await featureAbility.getContext().getOrCreateDistributedDir();
console.info('distribute dir is ' + dir) console.info('distribute dir is ' + dir)
} catch (error) { } catch (error) {
console.error('getOrCreateDistributedDir failed with ' + error) console.error('getOrCreateDistributedDir failed with ' + error);
} }
let fd: number; let fd: number;
let path = dir + "/a.txt"; let path = dir + "/a.txt";
fd = fileIo.openSync(path, 0o2 | 0o100, 0o666); fd = fs.openSync(path, fs.OpenMode.READ_WRITE).fd;
fileIo.close(fd); fs.close(fd);
})() })()
``` ```
# Using Want to Share Data Between Applications # Using Want to Share Data Between Applications
Users often need to share data (such as a text or an image) from one application to another. The following uses PDF file sharing as an example to describe how to use Want to share data between applications. Users often need to share data (such as a text or an image) from one application to another. The following uses PDF file sharing as an example to describe how to use Want to share data between applications.
Data sharing requires two UIAbility components (one for the sharing party and the other for the shared party) and one system component (used as the application sharing box). When the sharing party initiates data sharing by calling **startAbility()**, the system implicitly matches and displays all applications that support the type of data to share. After the user selects an application, the system starts the application to complete data sharing.
## Prerequisites In this section, data sharing is triggered by touching a button. You can use other ways to trigger data sharing during application development. This section focuses on how to configure Want to implement data sharing.
1. There are two UIAbility components (one for the sharing party and the other for the shared party) and one system component (used as the application selector). When the sharing party initiates data sharing through **startAbility()**, the application selector is started. The system implicitly matches and displays all applications that support the type of data to share. After the user selects an application, the system starts that application to complete data sharing. The following actions are involved for data sharing:
2. In this section, data sharing is triggered by touching a button. You can use other ways to trigger data sharing during application development. This section focuses on the Want configuration used for data sharing. - **ohos.want.action.select**: action of starting the application sharing box.
- **ohos.want.action.sendData**: action of sending a single data record, that is, transferring data to the shared party.
3. The following actions are involved in this section:
- **ACTION_SELECT (ohos.want.action.select)**: action of displaying the application selector. ## Sharing Party
- **ACTION_SEND_DATA (ohos.want.action.sendData)**: action of launching the UI for sending a single data record. It is used to transfer data to the shared party.
The sharing party starts an application sharing box and transfers the data to the shared party. Therefore, Want of the sharing party must be nested at two layers. In the first layer, implicit Want is used together with the **ohos.want.action.select** action to display the application sharing box. In the second layer, the data to share is declared
## How to Develop in the custom field **parameters**, and then the Want that includes the **ohos.want.action.sendData** action and the **parameters** field is transferred to the application sharing box. The shared party obtains the shared data from **parameters**.
- Sharing party ```ts
1. In the stage mode, the [File Descriptor (FD)](../reference/apis/js-apis-fileio.md#fileioopensync) is used for file transfer. This example assumes that the path of the file to share is obtained. import common from '@ohos.app.ability.common';
```ts let fileType = 'application/pdf';
import fileIO from '@ohos.fileio'; let fileName = 'TestFile.pdf';
let fileFd = -1; // Obtain the file descriptor (FD) of the file to share.
// let path = ... let fileSize; // Obtain the size of the file to share.
// Open the file whose path is a variable.
let fileFd = fileIO.openSync(path, 0o102, 0o666); function implicitStartAbility() {
``` let context = getContext(this) as common.UIAbilityContext;
let wantInfo = {
2. As described in the prerequisites, the sharing party starts an application selector and shares the data to the selector, and the selector transfers the data to the shared party. Want of the sharing party must be nested at two layers. At the first layer, implicit Want is used together with the **ohos.want.action.select** action to display the application selector. At the second layer, complete Want is declared in the custom field **parameters** to transfer the data to share. / This action is used to implicitly match the application sharing box.
action: 'ohos.want.action.select',
```ts // This is the custom parameter in the first layer of Want,
import wantConstant from '@ohos.app.ability.wantConstant'; / which is intended to add information to the application sharing box.
parameters: {
// let path = ... // MIME type of PDF.
// let fileFd = ... 'ability.picker.type': fileType,
// let fileSize = ... 'ability.picker.fileNames': [fileName],
let want = { 'ability.picker.fileSizes': [fileSize],
/ This action is used to implicitly match the application selector. // This is nested Want ,which will be directly sent to the selected application.
action: wantConstant.Action.ACTION_SELECT, 'ability.want.params.INTENT': {
// This is the custom parameter in the first layer of Want, 'action': 'ohos.want.action.sendData',
/ which is intended to add information to the application selector. 'type': 'application/pdf',
parameters: { 'parameters': {
// MIME type of PDF. 'keyFd': { 'type': 'FD', 'value': fileFd }
"ability.picker.type": "application/pdf", }
"ability.picker.fileNames": [path],
"ability.picker.fileSizes": [fileSize],
// This nested Want ,which will be directly sent to the selected application.
"ability.want.params.INTENT": {
"action": "ohos.want.action.sendData",
"type": "application/pdf",
"parameters": {
"keyFd": {"type": "FD", "value": fileFd}
}
}
}
} }
``` }
}
In the preceding code, the custom field **parameters** is used. The **ability.picker.\*** fields in the first-layer **parameters** are used to pass the information to be displayed on the application selector. The following fields are involved: context.startAbility(wantInfo).then(() => {
// ...
- **"ability.picker.type"**: The application selector renders the file type icon based on this field. }).catch((err) => {
- **"ability.picker.fileNames"**: The application selector displays the file name based on this field. // ...
- **"ability.picker.fileSizes"**: The application selector displays the file size based on this field. The unit is byte. })
- **"ability.picker.fileNames"** and **"ability.picker.fileSizes"** are arrays and have a one-to-one mapping. }
```
For example, when **"ability.picker.type"** is **"application/pdf"**, **"ability.picker.fileNames"** is **"["APIs.pdf"]"**, and **"ability.picker.fileSizes"** is **"[350 \* 1024]"**, the application selector is displayed as follows:
> **NOTE**
![stage-want2](figures/stage-want2.png) >
> Data sharing can be implemented only in FD format. For details about how to obtain the FD and file name, see [File Management](../reference/apis/js-apis-file-fs.md).
In the preceding code, the **ability.want.params.INTENT** field is nested Want. In this field, **action** and **type** are used for implicit matching by the application selector. For details about implicit matching, see [Matching Rules of Implicit Want](explicit-implicit-want-mappings.md#matching-rules-of-implicit-want). After the user selects an application, the nested Want of the **ability.want.params.INTENT** field is passed to that application.
In the preceding code, under the custom field **parameters**, the following **ability.picker.*** fields are used to pass the information to be displayed on the application sharing box:
- Shared party
1. As mentioned above, the application selector performs implicit matching based on the **ability.want.params.INTENT** field. Therefore, you must set **skills** in the ability configuration file (**module.json5** file in the stage model) of the shared party as follows: - **ability.picker.type**: file type icon.
- **ability.picker.fileNames**: file name.
```ts - **ability.picker.fileSizes**: file size, in bytes.
"skills": [ - **ability.picker.fileNames** and **ability.picker.fileSizes** are arrays and have a one-to-one mapping.
{
"entities": [ The following figure shows an example.
![stage-want2](figures/stage-want2.png)
## Shared Party
To enable the shared party to identify the shared content, configure **skills** in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility of the shared party. The **actions** and **type** fields in **uris** match the **action** and **type** fields in **ability.want.params.INTENT** of the sharing party, respectively.
```json
{
"module": {
// ...
"abilities": [
{
// ...
"skills": [
{
// ... // ...
], "actions": [
"actions": [ "action.system.home",
"ohos.want.action.sendData" "ohos.want.action.sendData"
// ... // ...
], ],
"uris": [ "uris": [
{ {
"type": "application/pdf" "type": "application/pdf"
}, },
// ... ]
] }
}, ]
]
```
The **actions** and **type** fields in **uris** match the **action** and **type** fields in **ability.want.params.INTENT**, respectively.
Files can be transferred in FD mode, but not URI mode. In implicit matching, the **type** field in Want must match the **type** field in **uris** under **skills** of the shared party. Therefore, specify only the **type** field in **uris**. If **host** and **port** are specified, the matching fails. The application selector initiates implicit matching based on **ability.want.params.INTENT**. Therefore, when the **uri** field added to **ability.want.params.INTENT** matches the **uris** field under **skills**, the matching is successful and additional data can be transferred.
2. After the application selector starts the shared party, the system calls **onCreate** and passes **ability.want.params.INTENT** to the **want** parameter.
```ts
onCreate(want, launchParam) {
// When keyFd is undefined, the application crashes.
if (want["parameters"]["keyFd"] !== undefined) {
// Receive the file descriptor.
let fd = want["parameters"]["keyFd"].value;
// ...
}
} }
``` ]
}
}
```
After the user selects an application, the Want nested in the **ability.want.params.INTENT** field is passed to that application. The UIAbility of the shared party, after being started, can call [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) to obtain the passed Want.
The following is an example of the Want obtained. You can use the FD of the shared file to perform required operations.
```json
{
"deviceId": "",
"bundleName": "com.example.myapplication",
"abilityName": "EntryAbility",
"moduleName": "entry",
"uri": "",
"type": "application/pdf",
"flags": 0,
"action": "ohos.want.action.sendData",
"parameters": {
"component.startup.newRules": true,
"keyFd": {
"type": "FD",
"value": 36
},
"mime-type": "application/pdf",
"moduleName": "entry",
"ohos.aafwk.param.callerPid": 3488,
"ohos.aafwk.param.callerToken": 537379209,
"ohos.aafwk.param.callerUid": 20010014
},
"entities": []
}
```
...@@ -4,9 +4,6 @@ Both explicit Want and implicit Want can be used to match an ability to start ba ...@@ -4,9 +4,6 @@ Both explicit Want and implicit Want can be used to match an ability to start ba
## Matching Rules of Explicit Want ## Matching Rules of Explicit Want
The table below describes the matching rules of explicit Want.
| Name| Type| Matching Item| Mandatory| Rule Description| | Name| Type| Matching Item| Mandatory| Rule Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| deviceId | string | Yes| No| If this field is unspecified, only abilities on the local device are matched.| | deviceId | string | Yes| No| If this field is unspecified, only abilities on the local device are matched.|
...@@ -22,8 +19,6 @@ The table below describes the matching rules of explicit Want. ...@@ -22,8 +19,6 @@ The table below describes the matching rules of explicit Want.
## Matching Rules for Implicit Want ## Matching Rules for Implicit Want
The table below describes the matching rules of implicit Want.
| Name | Type | Matching Item| Mandatory| Rule Description | | Name | Type | Matching Item| Mandatory| Rule Description |
| ----------- | ------------------------------ | ------ | ---- | ------------------------------------------------------------ | | ----------- | ------------------------------ | ------ | ---- | ------------------------------------------------------------ |
| deviceId | string | Yes | No | Implicit invoking is not supported across devices. | | deviceId | string | Yes | No | Implicit invoking is not supported across devices. |
...@@ -37,8 +32,9 @@ The table below describes the matching rules of implicit Want. ...@@ -37,8 +32,9 @@ The table below describes the matching rules of implicit Want.
| 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.| | 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. | | 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:
## Interpretation of Implicit Want Matching Rules
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 **want** parameter passed by the caller indicates the operation to be performed by the caller. It also provides data and application type restrictions.
...@@ -50,7 +46,7 @@ The system matches the **want** parameter (including the **action**, **entities* ...@@ -50,7 +46,7 @@ The system matches the **want** parameter (including the **action**, **entities*
### Matching Rules of action in the want Parameter ### Matching Rules of action in the want Parameter
The system matches the [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) attribute in the **want** parameter passed by the caller against **actions** under **skills** of the abilities. The system matches the **action** attribute in the **want** parameter passed by the caller against **actions** under **skills** of the abilities.
- If **action** in the passed **want** parameter is specified but **actions** under **skills** of an ability is unspecified, the matching fails. - If **action** in the passed **want** parameter is specified but **actions** under **skills** of an ability is unspecified, the matching fails.
...@@ -60,14 +56,14 @@ The system matches the [action](../reference/apis/js-apis-ability-wantConstant.m ...@@ -60,14 +56,14 @@ 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. - 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
![want-action](figures/want-action.png) ![want-action](figures/want-action.png)
### Matching Rules of entities in the want Parameter ### Matching Rules of entities in the want Parameter
The system matches the [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) attribute in the **want** parameter passed by the caller against **entities** under **skills** of the abilities. The system matches the **entities** attribute in the **want** parameter passed by the caller against **entities** under **skills** of the abilities.
- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an ability is specified, the matching is successful. - If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an ability is specified, the matching is successful.
...@@ -79,19 +75,15 @@ The system matches the [entities](../reference/apis/js-apis-ability-wantConstant ...@@ -79,19 +75,15 @@ The system matches the [entities](../reference/apis/js-apis-ability-wantConstant
- If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an ability is specified but does not contain **entities** in the passed **want** parameter, the matching fails. - If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an ability is specified but does not contain **entities** in the passed **want** parameter, the matching fails.
Figure 2 Matching rule of entities in the want parameter **Figure 2** Matching rule of entities in the want parameter
![want-entities](figures/want-entities.png) ![want-entities](figures/want-entities.png)
### Matching Rules of uri and type in the want Parameter ### Matching Rules of uri and type in the want Parameter
When the **uri** and **type** parameters are specified in the **want** parameter to initiate a component startup request, the system traverses the list of installed components and matches the **uris** array under **skills** of the abilities one by one. If one of the **uris** arrays under **skills** matches the **uri** and **type** in the passed **want**, the matching is successful. When the **uri** and **type** parameters are specified in the **want** parameter to initiate a component startup request, the system traverses the list of installed components and matches the **uris** array under **skills** of the abilities one by one. If one of the **uris** arrays under **skills** matches the **uri** and **type** in the passed **want**, the matching is successful.
Figure 3 Matching rules when uri and type are specified in the want parameter
![want-uri-type1](figures/want-uri-type1.png)
There are four combinations of **uri** and **type** settings. The matching rules are as follows: There are four combinations of **uri** and **type** settings. The matching rules are as follows:
- Neither **uri** or **type** is specified in the **want** parameter. - Neither **uri** or **type** is specified in the **want** parameter.
...@@ -111,13 +103,19 @@ There are four combinations of **uri** and **type** settings. The matching rules ...@@ -111,13 +103,19 @@ There are four combinations of **uri** and **type** settings. The matching rules
- If the **uris** array under **skills** of an ability is unspecified, the matching fails. - If the **uris** array under **skills** of an ability is unspecified, the matching fails.
- If the **uris** array under **skills** of an ability contains an element whose [uri is matched](#matching-rules-of-uri) and [type is matched](#matching-rules-of-type), the matching is successful. Otherwise, the matching fails. - If the **uris** array under **skills** of an ability contains an element whose [uri is matched](#matching-rules-of-uri) and [type is matched](#matching-rules-of-type), the matching is successful. Otherwise, the matching fails.
Leftmost URI matching: When only **scheme**, a combination of **scheme** and **host**, or a combination of **scheme**, **host**, and **port** is configured in the **uris** array under **skills** of the ability,
the matching is successful only if the leftmost URI in the passed **want** parameter matches **scheme**, the combination of **scheme** and **host**, or the combination of **scheme**, **host**, and **port**.
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 3** Matching rules when uri and type are specified in the want parameter
![want-uri-type1](figures/want-uri-type1.png)
Figure 4 Matching rules of uri and type in the want parameter 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
![want-uri-type2](figures/want-uri-type2.png) ![want-uri-type2](figures/want-uri-type2.png)
### Matching Rules of uri ### Matching Rules of uri
...@@ -128,7 +126,9 @@ To simplify the description, **uri** in the passed **want** parameter is called ...@@ -128,7 +126,9 @@ To simplify the description, **uri** in the passed **want** parameter is called
- If **host** of **s_uri** is unspecified and **scheme** of **w_uri** and **scheme** of **s_uri** are the same, the matching is successful. Otherwise, the matching fails. - If **host** of **s_uri** is unspecified and **scheme** of **w_uri** and **scheme** of **s_uri** are the same, the matching is successful. Otherwise, the matching fails.
- If **path**, **pathStartWith**, and **pathRegex** of **s_uri** are unspecified and **w_uri** and **s_uri** are the same, the matching is successful. Otherwise, the matching fails. - If **port** of **s_uri** is unspecified and the combination of **scheme** and **host** of **w_uri** is the same as the combination of **scheme** and **host** of **s_uri**, the matching is successful. Otherwise, the matching fails.
- If **path**, **pathStartWith**, and **pathRegex** of **s_uri** are unspecified and the combination of **scheme**, **host**, and **port** of **w_uri** is the same as the combination of **scheme**, **host**, and **port** of **s_uri**, the matching is successful. Otherwise, the matching fails.
- If **path** of **s_uri** is specified and the **full path expressions** of **w_uri** and **s_uri** are the same, the matching is successful. Otherwise, the matching of **pathStartWith** continues. - If **path** of **s_uri** is specified and the **full path expressions** of **w_uri** and **s_uri** are the same, the matching is successful. Otherwise, the matching of **pathStartWith** continues.
...@@ -139,12 +139,17 @@ To simplify the description, **uri** in the passed **want** parameter is called ...@@ -139,12 +139,17 @@ To simplify the description, **uri** in the passed **want** parameter is called
> **NOTE** > **NOTE**
> >
> The **scheme**, **host**, **port**, **path**, **pathStartWith**, and **pathRegex** attributes of **uris** under **skills** of an ability are concatenated. If **path**, **pathStartWith**, and **pathRegex** are declared in sequence, **uris** can be concatenated into the following expressions: > The **scheme**, **host**, **port**, **path**, **pathStartWith**, and **pathRegex** attributes of **uris** under **skills** of an ability are concatenated. If **path**, **pathStartWith**, and **pathRegex** are declared in sequence, **uris** can be concatenated into the following expressions:
>
> - **Full path expression**: scheme://host:port/path
>
> - **Prefix expression**: scheme://host:port/pathStartWith
>
> - **Regular expression**: scheme://host:port/pathRegex
> >
> - **Full path expression**: `scheme://host:port/path` > - **Prefix URI expression**: When only **scheme**, a combination of **scheme** and **host**, or a combination of **scheme**, **host**, and **port** is configured in the configuration file, the matching is successful if a URI prefixed with the configuration file is passed in.
> > * `scheme://`
> - **Prefix expression**: `scheme://host:port/pathStartWith` > * `scheme://host`
> > * `scheme://host:port`
> - **Regular expression**: `scheme://host:port/pathRegex`
### Matching Rules of type ### Matching Rules of type
......
# Cross-Device Migration (for System Applications Only)] # Cross-Device Migration (for System Applications Only)
## When to Use ## When to Use
......
...@@ -11,7 +11,7 @@ Multi-device coordination involves the following scenarios: ...@@ -11,7 +11,7 @@ Multi-device coordination involves the following scenarios:
- [Connecting to ServiceExtensionAbility Across Devices](#connecting-to-serviceextensionability-across-devices) - [Connecting to ServiceExtensionAbility Across Devices](#connecting-to-serviceextensionability-across-devices)
- [Using Cross-Device Ability Call](#using-cross-device-ability-call) - [Using Cross-Device Call](#using-cross-device-call)
## Multi-Device Collaboration Process ## Multi-Device Collaboration Process
...@@ -102,7 +102,7 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -102,7 +102,7 @@ On device A, touch the **Start** button provided by the initiator application to
abilityName: 'FuncAbility', abilityName: 'FuncAbility',
moduleName: 'module1', // moduleName is optional. moduleName: 'module1', // moduleName is optional.
} }
// context is the ability-level context of the initiator UIAbility. // context is the AbilityContext of the initiator UIAbility.
this.context.startAbility(want).then(() => { this.context.startAbility(want).then(() => {
// ... // ...
}).catch((err) => { }).catch((err) => {
...@@ -118,7 +118,7 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -118,7 +118,7 @@ On device A, touch the **Start** button provided by the initiator application to
### Available APIs ### Available APIs
**Table 2** APIs for starting an ability across devices and returning the result data **Table 2** APIs for starting a UIAbility across devices and returning the result data
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
...@@ -154,7 +154,7 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -154,7 +154,7 @@ On device A, touch the **Start** button provided by the initiator application to
abilityName: 'FuncAbility', abilityName: 'FuncAbility',
moduleName: 'module1', // moduleName is optional. moduleName: 'module1', // moduleName is optional.
} }
// context is the ability-level context of the initiator UIAbility. // context is the AbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(want).then((data) => { this.context.startAbilityForResult(want).then((data) => {
// ... // ...
}).catch((err) => { }).catch((err) => {
...@@ -174,7 +174,7 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -174,7 +174,7 @@ On device A, touch the **Start** button provided by the initiator application to
moduleName: 'module1', moduleName: 'module1',
}, },
} }
// context is the ability-level context of the target UIAbility. // context is the AbilityContext of the target UIAbility.
this.context.terminateSelfWithResult(abilityResult, (err) => { this.context.terminateSelfWithResult(abilityResult, (err) => {
// ... // ...
}); });
...@@ -187,7 +187,7 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -187,7 +187,7 @@ On device A, touch the **Start** button provided by the initiator application to
// ... // ...
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(want).then((data) => { this.context.startAbilityForResult(want).then((data) => {
if (data?.resultCode === RESULT_CODE) { if (data?.resultCode === RESULT_CODE) {
// Parse the information returned by the target UIAbility. // Parse the information returned by the target UIAbility.
...@@ -315,24 +315,24 @@ A system application can connect to a service on another device by calling [conn ...@@ -315,24 +315,24 @@ A system application can connect to a service on another device by calling [conn
``` ```
## Using Cross-Device Ability Call ## Using Cross-Device Call
The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction (for System Applications Only)](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction-for-system-applications-only). The basic principle of cross-device call is the same as that of intra-device call. For details, see [Using Call to Implement UIAbility Interaction (for System Applications Only)](uiability-intra-device-interaction.md#using-call-to-implement-uiability-interaction-for-system-applications-only).
The following describes how to implement multi-device collaboration through cross-device ability call. The following describes how to implement multi-device collaboration through cross-device call.
### Available APIs ### Available APIs
**Table 4** Ability call APIs **Table 4** Call APIs
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
| startAbilityByCall(want: Want): Promise&lt;Caller&gt;; | Starts a UIAbility in the foreground or background and obtains the caller object for communicating with the UIAbility.| | startAbilityByCall(want: Want): Promise&lt;Caller&gt;; | Starts a UIAbility in the foreground or background and obtains the caller object for communicating with the UIAbility.|
| on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.| | on(method: string, callback: CalleeCallBack): void | Callback invoked when the CalleeAbility registers a method.|
| off(method: string): void | Callback invoked when the callee ability deregisters a method.| | off(method: string): void | Callback invoked when the CalleeAbility deregisters a method.|
| call(method: string, data: rpc.Parcelable): Promise&lt;void&gt; | Sends agreed parcelable data to the callee ability.| | call(method: string, data: rpc.Parcelable): Promise&lt;void&gt; | Sends agreed parcelable data to the CalleeAbility.|
| callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageSequence&gt; | Sends agreed parcelable data to the callee ability and obtains the agreed parcelable data returned by the callee ability.| | callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageSequence&gt; | Sends agreed parcelable data to the CalleeAbility and obtains the agreed parcelable data returned by the CalleeAbility.|
| release(): void | Releases the caller object.| | release(): void | Releases the caller object.|
| on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.| | on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.|
...@@ -367,17 +367,17 @@ The following describes how to implement multi-device collaboration through cros ...@@ -367,17 +367,17 @@ The following describes how to implement multi-device collaboration through cros
} }
``` ```
3. Create the callee ability. 3. Create the CalleeAbility.
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 CalleeAbility, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener.
1. Configure the launch type of the UIAbility. 1. Configure the launch type of the UIAbility.
Set **launchType** of the callee ability to **singleton** in the **module.json5** file. Set **launchType** of the CalleeAbility to **singleton** in the **module.json5** file.
| JSON Field| Description| | JSON Field| Description|
| -------- | -------- | | -------- | -------- |
| "launchType"| Ability launch type. Set this parameter to **singleton**.| | "launchType"| UIAbility launch type. Set this parameter to **singleton**.|
An example of the UIAbility configuration is as follows: An example of the UIAbility configuration is as follows:
...@@ -401,7 +401,7 @@ The following describes how to implement multi-device collaboration through cros ...@@ -401,7 +401,7 @@ The following describes how to implement multi-device collaboration through cros
3. Define the agreed parcelable data. 3. Define the agreed parcelable data.
The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. The data formats sent and received by the CallerAbility and CalleeAbility must be consistent. In the following example, the data formats are number and string.
```ts ```ts
export default class MyParcelable { export default class MyParcelable {
...@@ -438,13 +438,13 @@ The following describes how to implement multi-device collaboration through cros ...@@ -438,13 +438,13 @@ The following describes how to implement multi-device collaboration through cros
function sendMsgCallback(data) { function sendMsgCallback(data) {
console.info('CalleeSortFunc called') console.info('CalleeSortFunc called')
// Obtain the parcelable data sent by the caller ability. // Obtain the parcelable data sent by the CallerAbility.
let receivedData = new MyParcelable(0, '') let receivedData = new MyParcelable(0, '')
data.readParcelable(receivedData) data.readParcelable(receivedData)
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`)
// Process the data. // Process the data.
// Return the parcelable data result to the caller ability. // Return the parcelable data result to the CallerAbility.
return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`) return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`)
} }
...@@ -467,7 +467,7 @@ The following describes how to implement multi-device collaboration through cros ...@@ -467,7 +467,7 @@ The following describes how to implement multi-device collaboration through cros
} }
``` ```
4. Obtain the caller object and access the callee ability. 4. Obtain the caller object and access the CalleeAbility.
1. Import the **UIAbility** module. 1. Import the **UIAbility** module.
```ts ```ts
...@@ -476,7 +476,7 @@ The following describes how to implement multi-device collaboration through cros ...@@ -476,7 +476,7 @@ The following describes how to implement multi-device collaboration through cros
2. Obtain the caller object. 2. Obtain the caller object.
The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. The **context** attribute of the UIAbility implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the UIAbility, uses **startAbilityByCall** to start the CalleeAbility, obtain the caller object, and register the **onRelease** listener of the CallerAbility. You need to implement processing based on service requirements.
```ts ```ts
async onButtonGetRemoteCaller() { async onButtonGetRemoteCaller() {
...@@ -491,7 +491,7 @@ The following describes how to implement multi-device collaboration through cros ...@@ -491,7 +491,7 @@ The following describes how to implement multi-device collaboration through cros
if (data != null) { if (data != null) {
caller = data caller = data
console.info('get remote caller success') console.info('get remote caller success')
// 注册caller的release监听 // Register the onRelease listener of the CallerAbility.
caller.onRelease((msg) => { caller.onRelease((msg) => {
console.info(`remote caller onRelease is called ${msg}`) console.info(`remote caller onRelease is called ${msg}`)
}) })
...@@ -505,8 +505,8 @@ The following describes how to implement multi-device collaboration through cros ...@@ -505,8 +505,8 @@ The following describes how to implement multi-device collaboration through cros
For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned). For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned).
5. Sends agreed parcelable data to the callee ability. 5. Sends agreed parcelable data to the CalleeAbility.
1. The parcelable data can be sent to the callee ability with or without a return value. The method and parcelable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability. 1. The parcelable data can be sent to the CalleeAbility with or without a return value. The method and parcelable data must be consistent with those of the CalleeAbility. The following example describes how to send data to the CalleeAbility.
```ts ```ts
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg'
...@@ -520,7 +520,7 @@ The following describes how to implement multi-device collaboration through cros ...@@ -520,7 +520,7 @@ The following describes how to implement multi-device collaboration through cros
} }
``` ```
2. In the following, **CallWithResult** is used to send data **originMsg** to the callee ability and assign the data processed by the **CallSendMsg** method to **backMsg**. 2. In the following, **CallWithResult** is used to send data **originMsg** to the CalleeAbility and assign the data processed by the **CallSendMsg** method to **backMsg**.
```ts ```ts
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg'
......
...@@ -28,10 +28,10 @@ Missions are managed by system applications (such as home screen), rather than t ...@@ -28,10 +28,10 @@ Missions are managed by system applications (such as home screen), rather than t
- Switch a mission to the foreground. - Switch a mission to the foreground.
A UIAbility instance corresponds to an independent mission. Therefore, when an application calls the **startAbility()** method to start a UIAbility, a mission is created. A UIAbility instance corresponds to an independent mission. Therefore, when an application calls **startAbility()** to start a UIAbility, a mission is created.
To call [missionManager](../reference/apis/js-apis-application-missionManager.md) to manage missions, the home screen application must request the **ohos.permission.MANAGE_MISSIONS** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). To call [missionManager](../reference/apis/js-apis-application-missionManager.md) to manage missions, the home screen application must request the **ohos.permission.MANAGE_MISSIONS** permission. For details about the configuration, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
You can use **missionManager** to manage missions, for example, listening for mission changes, obtaining mission information or snapshots, and clearing, locking, or unlocking missions. The sample code is as follows: You can use **missionManager** to manage missions, for example, listening for mission changes, obtaining mission information or snapshots, and clearing, locking, or unlocking missions. The sample code is as follows:
......
...@@ -17,7 +17,7 @@ This topic describes the UIAbility interaction modes in the following scenarios. ...@@ -17,7 +17,7 @@ This topic describes the UIAbility interaction modes in the following scenarios.
- [Starting a Specified Page of UIAbility](#starting-a-specified-page-of-uiability) - [Starting a Specified Page of UIAbility](#starting-a-specified-page-of-uiability)
- [Using Ability Call to Implement UIAbility Interaction (for System Applications Only)](#using-ability-call-to-implement-uiability-interaction-for-system-applications-only) - [Using Call to Implement UIAbility Interaction (for System Applications Only)](#using-call-to-implement-uiability-interaction-for-system-applications-only)
## Starting UIAbility in the Same Application ## Starting UIAbility in the Same Application
...@@ -38,7 +38,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func ...@@ -38,7 +38,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func
info: 'From the Index page of EntryAbility', info: 'From the Index page of EntryAbility',
}, },
} }
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbility(wantInfo).then(() => { this.context.startAbility(wantInfo).then(() => {
// ... // ...
}).catch((err) => { }).catch((err) => {
...@@ -54,7 +54,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func ...@@ -54,7 +54,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func
export default class FuncAbility extends UIAbility { export default class FuncAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
// Receive the parameters passed by the caller UIAbility. // Receive the parameters passed by the initiator UIAbility.
let funcAbilityWant = want; let funcAbilityWant = want;
let info = funcAbilityWant?.parameters?.info; let info = funcAbilityWant?.parameters?.info;
// ... // ...
...@@ -65,7 +65,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func ...@@ -65,7 +65,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func
3. To stop the **UIAbility** instance after the FuncAbility service is complete, call **terminateSelf()** in FuncAbility. 3. To stop the **UIAbility** instance after the FuncAbility service is complete, call **terminateSelf()** in FuncAbility.
```ts ```ts
// context is the ability-level context of the UIAbility instance to stop. // context is the UIAbilityContext of the UIAbility instance to stop.
this.context.terminateSelf((err) => { this.context.terminateSelf((err) => {
// ... // ...
}); });
...@@ -88,7 +88,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned ...@@ -88,7 +88,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned
info: 'From the Index page of EntryAbility', info: 'From the Index page of EntryAbility',
}, },
} }
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(wantInfo).then((data) => { this.context.startAbilityForResult(wantInfo).then((data) => {
// ... // ...
}).catch((err) => { }).catch((err) => {
...@@ -111,23 +111,23 @@ When starting FuncAbility from EntryAbility, you want the result to be returned ...@@ -111,23 +111,23 @@ When starting FuncAbility from EntryAbility, you want the result to be returned
}, },
}, },
} }
// context is the ability-level context of the callee UIAbility. // context is the AbilityContext of the target UIAbility.
this.context.terminateSelfWithResult(abilityResult, (err) => { this.context.terminateSelfWithResult(abilityResult, (err) => {
// ... // ...
}); });
``` ```
3. After FuncAbility stops itself, EntryAbility uses the **startAbilityForResult()** method to receive the information returned by FuncAbility. The value of **RESULT_CODE** must be the same as the preceding value. 3. After FuncAbility stops itself, EntryAbility uses **startAbilityForResult()** to receive the information returned by FuncAbility. The value of **RESULT_CODE** must be the same as the preceding value.
```ts ```ts
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
// ... // ...
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(want).then((data) => { this.context.startAbilityForResult(want).then((data) => {
if (data?.resultCode === RESULT_CODE) { if (data?.resultCode === RESULT_CODE) {
// Parse the information returned by the callee UIAbility. // Parse the information returned by the target UIAbility.
let info = data.want?.parameters?.info; let info = data.want?.parameters?.info;
// ... // ...
} }
...@@ -139,13 +139,13 @@ When starting FuncAbility from EntryAbility, you want the result to be returned ...@@ -139,13 +139,13 @@ When starting FuncAbility from EntryAbility, you want the result to be returned
## Starting UIAbility of Another Application ## Starting UIAbility of Another Application
Generally, the user only needs to do a common operation (for example, selecting a document application to view the document content) to start the UIAbility of another application. The [implicit Want launch mode](want-overview.md#types-of-want) is recommended. The system identifies a matched UIAbility and starts it based on the **want** parameter of the caller. Generally, the user only needs to do a common operation (for example, selecting a document application to view the document content) to start the UIAbility of another application. The [implicit Want launch mode](want-overview.md#types-of-want) is recommended. The system identifies a matched UIAbility and starts it based on the **want** parameter of the initiator UIAbility.
There are two ways to start **UIAbility**: [explicit and implicit](want-overview.md). There are two ways to start **UIAbility**: [explicit and implicit](want-overview.md).
- Explicit Want launch: This mode is used to start a determined UIAbility component of an application. You need to set **bundleName** and **abilityName** of the target application in the **want** parameter. - Explicit Want launch: This mode is used to start a determined UIAbility component of an application. You need to set **bundleName** and **abilityName** of the target application in the **want** parameter.
- Implicit Want launch: The user selects a UIAbility to start based on the matching conditions. That is, the UIAbility to start is not determined (the **abilityName** parameter is not specified). When the **startAbility()** method is called, the **want** parameter specifies a series of parameters such as [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction). **entities** provides additional type information of the target UIAbility, such as the browser or video player. **actions** specifies the common operations to perform, such as viewing, sharing, and application details. Then the system analyzes the **want** parameter to find the right UIAbility to start. You usually do not know whether the target application is installed and what **bundleName** and **abilityName** of the target application are. Therefore, implicit Want launch is usually used to start the UIAbility of another application. - Implicit Want launch: The user selects a UIAbility to start based on the matching conditions. That is, the UIAbility to start is not determined (the **abilityName** parameter is not specified). When **startAbility()** is called, the **want** parameter specifies a series of parameters such as [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction). **entities** provides category information of the target UIAbility, such as the browser or video player. **actions** specifies the common operations to perform, such as viewing, sharing, and application details. Then the system analyzes the **want** parameter to find the right UIAbility to start. You usually do not know whether the target application is installed and what **bundleName** and **abilityName** of the target application are. Therefore, implicit Want launch is usually used to start the UIAbility of another application.
This section describes how to start the UIAbility of another application through implicit Want. This section describes how to start the UIAbility of another application through implicit Want.
...@@ -175,7 +175,7 @@ This section describes how to start the UIAbility of another application through ...@@ -175,7 +175,7 @@ This section describes how to start the UIAbility of another application through
} }
``` ```
2. Include **entities** and **actions** of the caller's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). 2. Include **entities** and **actions** of the initiator UIAbility's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts ```ts
let wantInfo = { let wantInfo = {
...@@ -187,7 +187,7 @@ This section describes how to start the UIAbility of another application through ...@@ -187,7 +187,7 @@ This section describes how to start the UIAbility of another application through
entities: ['entity.system.default'], entities: ['entity.system.default'],
} }
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbility(wantInfo).then(() => { this.context.startAbility(wantInfo).then(() => {
// ... // ...
}).catch((err) => { }).catch((err) => {
...@@ -202,7 +202,7 @@ This section describes how to start the UIAbility of another application through ...@@ -202,7 +202,7 @@ This section describes how to start the UIAbility of another application through
3. To stop the **UIAbility** instance after the document application is used, call **terminateSelf()**. 3. To stop the **UIAbility** instance after the document application is used, call **terminateSelf()**.
```ts ```ts
// context is the ability-level context of the UIAbility instance to stop. // context is the AbilityContext of the UIAbility instance to stop.
this.context.terminateSelf((err) => { this.context.terminateSelf((err) => {
// ... // ...
}); });
...@@ -211,7 +211,7 @@ This section describes how to start the UIAbility of another application through ...@@ -211,7 +211,7 @@ This section describes how to start the UIAbility of another application through
## Starting UIAbility of Another Application and Obtaining the Return Result ## Starting UIAbility of Another Application and Obtaining the Return Result
If you want to obtain the return result when using implicit Want to start the UIAbility of another application, use the **startAbilityForResult()** method. An example scenario is that the main application needs to start a third-party payment application and obtain the payment result. If you want to obtain the return result when using implicit Want to start the UIAbility of another application, use **startAbilityForResult()**. An example scenario is that the main application needs to start a third-party payment application and obtain the payment result.
1. In the **module.json5** file of the UIAbility corresponding to the payment application, set [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) under **skills**. 1. In the **module.json5** file of the UIAbility corresponding to the payment application, set [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) under **skills**.
...@@ -239,7 +239,7 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -239,7 +239,7 @@ If you want to obtain the return result when using implicit Want to start the UI
} }
``` ```
2. Call the **startAbilityForResult()** method to start the UIAbility of the payment application. Include **entities** and **actions** of the caller's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. Use **data** in the asynchronous callback to receive the information returned to the caller after the payment UIAbility stops itself. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select. 2. Call **startAbilityForResult()** to start the UIAbility of the payment application. Include **entities** and **actions** of the initiator UIAbility's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. Use **data** in the asynchronous callback to receive the information returned to the initiator UIAbility after the payment UIAbility stops itself. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select.
```ts ```ts
let wantInfo = { let wantInfo = {
...@@ -251,7 +251,7 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -251,7 +251,7 @@ If you want to obtain the return result when using implicit Want to start the UI
entities: ['entity.system.default'], entities: ['entity.system.default'],
} }
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(wantInfo).then((data) => { this.context.startAbilityForResult(wantInfo).then((data) => {
// ... // ...
}).catch((err) => { }).catch((err) => {
...@@ -259,7 +259,7 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -259,7 +259,7 @@ If you want to obtain the return result when using implicit Want to start the UI
}) })
``` ```
3. After the payment is finished, call the **terminateSelfWithResult()** method to stop the payment UIAbility and return the **abilityResult** parameter. 3. After the payment is finished, call **terminateSelfWithResult()** to stop the payment UIAbility and return the **abilityResult** parameter.
```ts ```ts
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
...@@ -274,13 +274,13 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -274,13 +274,13 @@ If you want to obtain the return result when using implicit Want to start the UI
}, },
}, },
} }
// context is the ability-level context of the callee UIAbility. // context is the AbilityContext of the target UIAbility.
this.context.terminateSelfWithResult(abilityResult, (err) => { this.context.terminateSelfWithResult(abilityResult, (err) => {
// ... // ...
}); });
``` ```
4. Receive the information returned by the payment application in the callback of the **startAbilityForResult()** method. The value of **RESULT_CODE** must be the same as that returned by **terminateSelfWithResult()**. 4. Receive the information returned by the payment application in the callback of **startAbilityForResult()**. The value of **RESULT_CODE** must be the same as that returned by **terminateSelfWithResult()**.
```ts ```ts
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
...@@ -289,10 +289,10 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -289,10 +289,10 @@ If you want to obtain the return result when using implicit Want to start the UI
// Want parameter information. // Want parameter information.
}; };
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(want).then((data) => { this.context.startAbilityForResult(want).then((data) => {
if (data?.resultCode === RESULT_CODE) { if (data?.resultCode === RESULT_CODE) {
// Parse the information returned by the callee UIAbility. // Parse the information returned by the target UIAbility.
let payResult = data.want?.parameters?.payResult; let payResult = data.want?.parameters?.payResult;
// ... // ...
} }
...@@ -309,7 +309,7 @@ A UIAbility component can have multiple pages. When it is started in different s ...@@ -309,7 +309,7 @@ A UIAbility component can have multiple pages. When it is started in different s
### Specifying a Startup Page ### Specifying a Startup Page
When the caller UIAbility starts another UIAbility, it usually needs to redirect to a specified page. For example, FuncAbility contains two pages: Index (corresponding to the home page) and Second (corresponding to function A page). You can configure the specified page URL in the **want** parameter by adding a custom parameter to **parameters** in **want**. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). When the initiator UIAbility starts another UIAbility, it usually needs to redirect to a specified page. For example, FuncAbility contains two pages: Index (corresponding to the home page) and Second (corresponding to function A page). You can configure the specified page URL in the **want** parameter by adding a custom parameter to **parameters** in **want**. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts ```ts
...@@ -322,7 +322,7 @@ let wantInfo = { ...@@ -322,7 +322,7 @@ let wantInfo = {
router: 'funcA', router: 'funcA',
}, },
} }
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbility(wantInfo).then(() => { this.context.startAbility(wantInfo).then(() => {
// ... // ...
}).catch((err) => { }).catch((err) => {
...@@ -344,12 +344,12 @@ export default class FuncAbility extends UIAbility { ...@@ -344,12 +344,12 @@ export default class FuncAbility extends UIAbility {
funcAbilityWant; funcAbilityWant;
onCreate(want, launchParam) { onCreate(want, launchParam) {
// Receive the parameters passed by the caller UIAbility. // Receive the parameters passed by the initiator UIAbility.
this.funcAbilityWant = want; this.funcAbilityWant = want;
} }
onWindowStageCreate(windowStage: Window.WindowStage) { onWindowStageCreate(windowStage: Window.WindowStage) {
// Main window is created. Set a main page for this ability. // Main window is created. Set a main page for this UIAbility.
let url = 'pages/Index'; let url = 'pages/Index';
if (this.funcAbilityWant?.parameters?.router) { if (this.funcAbilityWant?.parameters?.router) {
if (this.funcAbilityWant.parameters.router === 'funA') { if (this.funcAbilityWant.parameters.router === 'funA') {
...@@ -379,7 +379,7 @@ In summary, when a UIAbility instance of application A has been created and the ...@@ -379,7 +379,7 @@ In summary, when a UIAbility instance of application A has been created and the
export default class FuncAbility extends UIAbility { export default class FuncAbility extends UIAbility {
onNewWant(want, launchParam) { onNewWant(want, launchParam) {
// Receive the parameters passed by the caller UIAbility. // Receive the parameters passed by the initiator UIAbility.
globalThis.funcAbilityWant = want; globalThis.funcAbilityWant = want;
// ... // ...
} }
...@@ -412,81 +412,83 @@ In summary, when a UIAbility instance of application A has been created and the ...@@ -412,81 +412,83 @@ In summary, when a UIAbility instance of application A has been created and the
``` ```
> **NOTE** > **NOTE**
> When the [launch type of the callee UIAbility](uiability-launch-type.md) is set to **standard**, a new instance is created each time the callee UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked. >
> When the [launch type of the target UIAbility](uiability-launch-type.md) is set to **standard**, a new instance is created each time the target UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked.
## Using Ability Call to Implement UIAbility Interaction (for System Applications Only) ## Using Call to Implement UIAbility Interaction (for System Applications Only)
Ability call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two UIAbility instances (caller ability and callee ability) through IPC. Call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility invoked can be either started in the foreground or created and run in the background. You can use the call to implement data sharing between two UIAbility instances (CallerAbility and CalleeAbility) through IPC.
The core API used for the ability call is **startAbilityByCall**, which differs from **startAbility** in the following ways: The core API used for the call is **startAbilityByCall**, which differs from **startAbility** in the following ways:
- **startAbilityByCall** supports ability launch in the foreground and background, whereas **startAbility** supports ability launch in the foreground only. - **startAbilityByCall** supports UIAbility launch in the foreground and background, whereas **startAbility** supports UIAbility launch in the foreground only.
- The caller ability can use the caller object returned by **startAbilityByCall** to communicate with the callee ability, but **startAbility** does not provide the communication capability. - The CallerAbility can use the caller object returned by **startAbilityByCall** to communicate with the CalleeAbility, but **startAbility** does not provide the communication capability.
Ability call is usually used in the following scenarios: Call is usually used in the following scenarios:
- Communicating with the callee ability - Communicating with the CalleeAbility
- Starting the callee ability in the background - Starting the CalleeAbility in the background
**Table 1** Terms used in the ability call **Table 1** Terms used in the call
| **Term**| Description| | **Term**| Description|
| -------- | -------- | | -------- | -------- |
| CallerAbility | UIAbility that triggers the ability call.| | CallerAbility | UIAbility that triggers the call.|
| CalleeAbility | UIAbility invoked by the ability call.| | CalleeAbility | UIAbility invoked by the call.|
| Caller | Object returned by **startAbilityByCall** and used by the caller ability to communicate with the callee ability.| | Caller | Object returned by **startAbilityByCall** and used by the CallerAbility to communicate with the CalleeAbility.|
| Callee | Object held by the callee ability to communicate with the caller ability.| | Callee | Object held by the CalleeAbility to communicate with the CallerAbility.|
The following figure shows the ability call process. The following figure shows the call process.
Figure 1 Ability call process Figure 1 Call process
![call](figures/call.png) ![call](figures/call.png)
- The caller ability uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the callee ability. - The CallerAbility uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the CalleeAbility.
- The callee ability, which holds a **Callee** object, uses **on()** of the **Callee** object to register a callback. This callback is invoked when the callee ability receives data from the caller ability. - The CalleeAbility, which holds a **Callee** object, uses **on()** of the **Callee** object to register a callback. This callback is invoked when the CalleeAbility receives data from the CallerAbility.
> **NOTE** > **NOTE**
> 1. Currently, only system applications can use the ability call. > 1. Currently, only system applications can use the call.
> >
> 2. The launch type of the callee ability must be **singleton**. > 2. The launch type of the CalleeAbility must be **singleton**.
> >
> 3. Both local (intra-device) and cross-device ability calls are supported. The following describes how to initiate a local call. For details about how to initiate a cross-device ability call, see [Using Cross-Device Ability Call](hop-multi-device-collaboration.md#using-cross-device-ability-call). > 3. Both local (intra-device) and cross-device calls are supported. The following describes how to initiate a local call. For details about how to initiate a cross-device call, see [Using Cross-Device Call](hop-multi-device-collaboration.md#using-cross-device-call).
### Available APIs ### Available APIs
The following table describes the main APIs used for the ability call. For details, see [AbilityContext](../reference/apis/js-apis-app-ability-uiAbility.md#caller). The following table describes the main APIs used for the call. For details, see [AbilityContext](../reference/apis/js-apis-app-ability-uiAbility.md#caller).
**Table 2** Ability call APIs **Table 2** Call APIs
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
| startAbilityByCall(want: Want): Promise&lt;Caller&gt; | Starts a UIAbility in the foreground (through the **want** configuration) or background (default) and obtains the caller object for communication with the UIAbility. For details, see [AbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartabilitybycall).| | startAbilityByCall(want: Want): Promise&lt;Caller&gt; | Starts a UIAbility in the foreground (through the **want** configuration) or background (default) and obtains the caller object for communication with the UIAbility. For details, see [AbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartabilitybycall).|
| on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.| | on(method: string, callback: CalleeCallBack): void | Callback invoked when the CalleeAbility registers a method.|
| off(method: string): void | Callback invoked when the callee ability deregisters a method.| | off(method: string): void | Callback invoked when the CalleeAbility deregisters a method.|
| call(method:&nbsp;string,&nbsp;data:&nbsp;rpc.Parcelable):&nbsp;Promise&lt;void&gt; | Sends agreed parcelable data to the callee ability.| | call(method: string, data: rpc.Parcelable): Promise&lt;void&gt; | Sends agreed parcelable data to the CalleeAbility.|
| callWithResult(method:&nbsp;string,&nbsp;data:&nbsp;rpc.Parcelable):&nbsp;Promise&lt;rpc.MessageSequence&gt; | Sends agreed parcelable data to the callee ability and obtains the agreed parcelable data returned by the callee ability.| | callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageSequence&gt; | Sends agreed parcelable data to the CalleeAbility and obtains the agreed parcelable data returned by the CalleeAbility.|
| release(): void | Releases the caller object.| | release(): void | Releases the caller object.|
| on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.| | on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.|
The implementation of using the ability call for UIAbility interaction involves two parts. The implementation of using the call for UIAbility interaction involves two parts.
- [Creating a Callee Ability](#creating-a-callee-ability) - [Creating a CalleeAbility](#creating-a-calleeability)
- [Accessing the Callee Ability](#accessing-the-callee-ability) - [Accessing the CalleeAbility](#accessing-the-calleeability)
### Creating a Callee Ability ### Creating a CalleeAbility
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 CalleeAbility, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener.
1. Configure the ability launch type. 1. Configure the launch type of the UIAbility.
Set **launchType** of the callee ability to **singleton** in the **module.json5** file.
Set **launchType** of the CalleeAbility to **singleton** in the **module.json5** file.
| JSON Field| Description| | JSON Field| Description|
| -------- | -------- | | -------- | -------- |
...@@ -514,7 +516,8 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -514,7 +516,8 @@ For the callee ability, implement the callback to receive data and the methods t
``` ```
3. Define the agreed parcelable data. 3. Define the agreed parcelable data.
The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string.
The data formats sent and received by the CallerAbility and CalleeAbility must be consistent. In the following example, the data formats are number and string.
```ts ```ts
...@@ -542,7 +545,8 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -542,7 +545,8 @@ For the callee ability, implement the callback to receive data and the methods t
``` ```
4. Implement **Callee.on** and **Callee.off**. 4. Implement **Callee.on** and **Callee.off**.
The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows:
The time to register a listener for the CalleeAbility depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the UIAbility and deregistered in **onDestroy**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows:
```ts ```ts
...@@ -552,13 +556,13 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -552,13 +556,13 @@ For the callee ability, implement the callback to receive data and the methods t
function sendMsgCallback(data) { function sendMsgCallback(data) {
console.info('CalleeSortFunc called'); console.info('CalleeSortFunc called');
// Obtain the parcelable data sent by the caller ability. // Obtain the parcelable data sent by the CallerAbility.
let receivedData = new MyParcelable(0, ''); let receivedData = new MyParcelable(0, '');
data.readParcelable(receivedData); data.readParcelable(receivedData);
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`);
// Process the data. // Process the data.
// Return the parcelable data result to the caller ability. // Return the parcelable data result to the CallerAbility.
return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`); return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`);
} }
...@@ -582,7 +586,7 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -582,7 +586,7 @@ For the callee ability, implement the callback to receive data and the methods t
``` ```
### Accessing the Callee Ability ### Accessing the CalleeAbility
1. Import the **UIAbility** module. 1. Import the **UIAbility** module.
...@@ -591,11 +595,12 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -591,11 +595,12 @@ For the callee ability, implement the callback to receive data and the methods t
``` ```
2. Obtain the caller interface. 2. Obtain the caller interface.
The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements.
The **UIAbilityContext** attribute implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **UIAbilityContext**, uses **startAbilityByCall** to start the CalleeAbility, obtain the caller object, and register the **onRelease** listener of the CallerAbility. You need to implement processing based on service requirements.
```ts ```ts
// Register the onRelease() listener of the caller ability. // Register the onRelease() listener of the CallerAbility.
private regOnRelease(caller) { private regOnRelease(caller) {
try { try {
caller.on("release", (msg) => { caller.on("release", (msg) => {
......
...@@ -77,9 +77,9 @@ The **specified** mode is used in some special scenarios. For example, in a docu ...@@ -77,9 +77,9 @@ The **specified** mode is used in some special scenarios. For example, in a docu
![uiability-launch-type2](figures/uiability-launch-type2.png) ![uiability-launch-type2](figures/uiability-launch-type2.png)
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. For example, there are two UIAbility components: EntryAbility and SpecifiedAbility (with the launch type **specified**). You are required to start SpecifiedAbility from EntryAbility.
1. In SpecifiedAbility, set the **launchType** field in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **specified**. 1. In SpecifiedAbility, set the **launchType** field in the [module.json5 file](../quick-start/module-configuration-file.md) to **specified**.
```json ```json
{ {
...@@ -95,8 +95,7 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of ...@@ -95,8 +95,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. 2. Create a unique string key for the instance. Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the application, based on the key, identifies the UIAbility instance used to respond to the request. In EntryAbility, add a custom parameter, for example, **instanceKey**, to the [want](want-overview.md) parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to distinguish the UIAbility instance.
In EntryAbility, add a custom parameter, for example, **instanceKey**, to the [want](want-overview.md) parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to distinguish the UIAbility instances.
```ts ```ts
// Configure an independent key for each UIAbility instance. // Configure an independent key for each UIAbility instance.
...@@ -114,7 +113,7 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of ...@@ -114,7 +113,7 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of
instanceKey: getInstance(), instanceKey: getInstance(),
}, },
} }
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbility(want).then(() => { this.context.startAbility(want).then(() => {
// ... // ...
}).catch((err) => { }).catch((err) => {
...@@ -133,7 +132,7 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of ...@@ -133,7 +132,7 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of
// In the AbilityStage instance of the callee, a key value corresponding to a UIAbility instance is returned for UIAbility whose launch type is specified. // In the AbilityStage instance of the callee, a key value corresponding to a UIAbility instance is returned for UIAbility whose launch type is specified.
// In this example, SpecifiedAbility of module1 is returned. // In this example, SpecifiedAbility of module1 is returned.
if (want.abilityName === 'SpecifiedAbility') { if (want.abilityName === 'SpecifiedAbility') {
// The returned string key is a custom string. // The returned key string is a custom string.
return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`; return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`;
} }
...@@ -147,16 +146,13 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of ...@@ -147,16 +146,13 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of
> 1. Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **specified**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, and the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) matches a created UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not. > 1. Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **specified**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, and the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) matches a created UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not.
> 2. AbilityStage is not automatically generated in the default project of DevEco Studio. For details about how to create an AbilityStage file, see [AbilityStage Component Container](abilitystage.md). > 2. AbilityStage is not automatically generated in the default project of DevEco Studio. For details about how to create an AbilityStage file, see [AbilityStage Component Container](abilitystage.md).
For example, in the document application, different key values are bound to different document instances. Each time a document is created, a new key value (for example, file path) is passed, and a new UIAbility instance is created when UIAbility is started in AbilityStage. However, when you open an existing document, the same UIAbility instance is started again in AbilityStage. For example, in the document application, different keys are bound to different document instances. Each time a document is created, a new key (for example, file path) is passed, and a new UIAbility instance is created when UIAbility is started in AbilityStage. However, when you open an existing document, the same UIAbility instance is started again in AbilityStage.
The following steps are used as an example.
The following steps are used as an example.
1. Open file A. A UIAbility instance, for example, UIAbility instance 1, is started. 1. Open file A. A UIAbility instance, for example, UIAbility instance 1, is started.
2. Close the process of file A in **Recents**. UIAbility instance 1 is destroyed. Return to the home screen and open file A again. A new UIAbility instance is started, for example, UIAbility instance 2. 2. Close the process of file A in **Recents**. UIAbility instance 1 is destroyed. Return to the home screen and open file A again. A new UIAbility instance is started, for example, UIAbility instance 2.
3. Return to the home screen and open file B. A new UIAbility instance is started, for example, UIAbility instance 3. 3. Return to the home screen and open file B. A new UIAbility instance is started, for example, UIAbility instance 3.
4. Return to the home screen and open file A again. UIAbility instance 2 is started. 4. Return to the home screen and open file A again. UIAbility instance 2 is started.
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册