diff --git a/en/application-dev/application-models/Readme-EN.md b/en/application-dev/application-models/Readme-EN.md index d2bca637ca2d62cc7a6ea5ca64a9f55cdf5793f0..2d70222630a25f38b0f66367e46fcfdef2487091 100644 --- a/en/application-dev/application-models/Readme-EN.md +++ b/en/application-dev/application-models/Readme-EN.md @@ -18,7 +18,6 @@ - [ExtensionAbility Component Overview](extensionability-overview.md) - [ServiceExtensionAbility](serviceextensionability.md) - [DataShareExtensionAbility (for System Applications Only)](datashareextensionability.md) - - [FormExtensionAbility (Widget)](widget-development-stage.md) - [AccessibilityExtensionAbility](accessibilityextensionability.md) - [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md) - [InputMethodExtensionAbility](inputmethodextentionability.md) diff --git a/en/application-dev/application-models/ability-startup-with-explicit-want.md b/en/application-dev/application-models/ability-startup-with-explicit-want.md index cb4642d108382c48a2e2b2285adfafc1df99d62b..80b96ce801bed7d8ae79aa2b3ddc566f10fc2bcf 100644 --- a/en/application-dev/application-models/ability-startup-with-explicit-want.md +++ b/en/application-dev/application-models/ability-startup-with-explicit-want.md @@ -1,73 +1,5 @@ # 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. - - -## 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 > src > main > 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. - - startAbilityWtExplicitWant +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). diff --git a/en/application-dev/application-models/ability-startup-with-implicit-want.md b/en/application-dev/application-models/ability-startup-with-implicit-want.md index 6550e5c628c642cf227cfde5f74eef7b61c8a52b..e3c94b2963e73aaa896eb5691a2af1932aba7d3c 100644 --- a/en/application-dev/application-models/ability-startup-with-implicit-want.md +++ b/en/application-dev/application-models/ability-startup-with-implicit-want.md @@ -1,77 +1,78 @@ # Using Implicit Want to Open a Website - -## Prerequisites - -One or more browsers are installed on your device. - -The **module.json5** of a browser application is as follows: +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: ```json -"skills": [ - { - "entities": [ - "entity.system.browsable" - // ... - ], - "actions": [ - "ohos.want.action.viewData" - // ... - ], - "uris": [ - { - "scheme": "https", - "host": "www.test.com", - "port": "8080", - // Prefix matching is used. - "pathStartWith": "query", - "type": "text/*" - }, +{ + "module": { + // ... + "abilities": [ { - "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. - - ```ts - async implicitStartAbility() { - try { - let want = { - // Uncomment the line below if you want to implicitly query data only in the specific bundle. - // bundleName: "com.example.myapplication", - "action": "ohos.want.action.viewData", - // entities can be omitted. - "entities": [ "entity.system.browsable" ], - "uri": "https://www.test.com:8080/query/student", - "type": "text/plain" - } - 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. +function implicitStartAbility() { + let context = getContext(this) as common.UIAbilityContext; + let wantInfo = { + // Uncomment the line below if you want to implicitly query data only in the specific bundle. + // bundleName: 'com.example.myapplication', + 'action': 'ohos.want.action.viewData', + // entities can be omitted. + 'entities': ['entity.system.browsable'], + 'uri': 'https://www.test.com:8080/query/student' + } + context.startAbility(wantInfo).then(() => { + // ... + }).catch((err) => { + // ... + }) +} +``` - 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) diff --git a/en/application-dev/application-models/application-context-stage.md b/en/application-dev/application-models/application-context-stage.md index 23bd8d29ec742f7591d8f7982245cc17ddc770ec..aa40d3aedf9dbb3db775a634dbd81f60f22fed51 100644 --- a/en/application-dev/application-models/application-context-stage.md +++ b/en/application-dev/application-models/application-context-stage.md @@ -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**. - The figure below illustrates the inheritance relationship of contexts. - + ![context-inheritance](figures/context-inheritance.png) - The figure below illustrates the holding relationship of contexts. - + ![context-holding](figures/context-holding.png) - 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 import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - let uiAbilityContext = this.context; - // ... - } + onCreate(want, launchParam) { + 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. ```ts import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; export default class MyService extends ServiceExtensionAbility { - onCreate(want) { - let serviceExtensionContext = this.context; - // ... - } + onCreate(want) { + 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**. ```ts - import AbilityStage from "@ohos.app.ability.AbilityStage"; + import AbilityStage from '@ohos.app.ability.AbilityStage'; export default class MyAbilityStage extends AbilityStage { - onCreate() { - let abilityStageContext = this.context; - // ... - } + onCreate() { + 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 import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - let applicationContext = this.context.getApplicationContext(); - // ... - } + onCreate(want, launchParam) { + let applicationContext = this.context.getApplicationContext(); + // ... + } } ``` @@ -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 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) -- [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 @@ -80,13 +84,13 @@ The following table describes the application development paths obtained from co | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| cacheDir | string | Yes| No| Cache directory of the application on the internal storage.
It is the content of **Storage** of an application under **Settings > Apps & services > Apps**.| -| tempDir | string | Yes| No| Temporary file directory of the application.
Files in this directory are deleted after the application is uninstalled.| -| filesDir | string | Yes| No| File directory of the application on the internal storage.
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.| -| 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. | -| distributedFilesDir | string | Yes| No| Storage directory of distributed application data files.| -| preferencesDir | string | Yes| Yes| Preferences directory of the application.| +| bundleCodeDir | string | Yes | No | Path for storing the application's installation package, that is, installation directory of the application on the internal storage. | +| cacheDir | string | Yes| No| Path for storing the application's cache files, that is, cache directory of the application on the internal storage.
It is the content of **Storage** of an application under **Settings > Apps & services > Apps**.| +| filesDir | string | Yes | No | Path for storing the application's common files, that is, file directory of the application on the internal storage.
Files in this directory may be synchronized to other directories during application migration or backup.| +| preferencesDir | string | Yes | Yes | Path for storing the application's preference files, that is, preferences directory of the application. | +| tempDir | string | Yes | No | Path for storing the application's temporary files.
Files in this directory are deleted after the application is uninstalled.| +| databaseDir | string | Yes | No | Path for storing the application's database, that is, storage directory of the local database. | +| 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. @@ -111,7 +115,7 @@ The capability of obtaining the application development path is provided by the | bundleCodeDir | {Path prefix}/el1/bundle/| | cacheDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/cache/| | 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/| | databaseDir | {Path prefix}/{Encryption level}/database/**{moduleName}**/| | distributedFilesDir | {Path prefix}/el2/distributedFiles/**{moduleName}**/| @@ -123,83 +127,92 @@ The sample code for obtaining the application development paths is as follows: import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - let cacheDir = this.context.cacheDir; - let tempDir = this.context.tempDir; - let filesDir = this.context.filesDir; - let databaseDir = this.context.databaseDir; - let bundleCodeDir = this.context.bundleCodeDir; - let distributedFilesDir = this.context.distributedFilesDir; - let preferencesDir = this.context.preferencesDir; - // ... - } + onCreate(want, launchParam) { + let cacheDir = this.context.cacheDir; + let tempDir = this.context.tempDir; + let filesDir = this.context.filesDir; + let databaseDir = this.context.databaseDir; + let bundleCodeDir = this.context.bundleCodeDir; + let distributedFilesDir = this.context.distributedFilesDir; + 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 ** 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 import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - // Before storing common information, switch the encryption level to EL1. - if (this.context.area === 1) {// Obtain 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. + onCreate(want, launchParam) { + // Before storing common information, switch the encryption level to EL1. + if (this.context.area === 1) {// Obtain 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. + } } ``` ### 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. > **NOTE** > > 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. - + For example, application information displayed on the home screen includes the application name and icon. The home screen application calls the foregoing method to obtain the context information, so as to obtain the resource information including the application name and icon. - + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - let bundleName2 = "com.example.application"; - let context2 = this.context.createBundleContext(bundleName2); - let label2 = context2.applicationInfo.label; - // ... - } + onCreate(want, launchParam) { + let bundleName2 = 'com.example.application'; + let context2 = this.context.createBundleContext(bundleName2); + 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. > **NOTE** > > 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. @@ -207,12 +220,12 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - let bundleName2 = "com.example.application"; - let moduleName2 = "module1"; - let context2 = this.context.createModuleContext(bundleName2, moduleName2); - // ... - } + onCreate(want, launchParam) { + let bundleName2 = 'com.example.application'; + let moduleName2 = 'module1'; + let context2 = this.context.createModuleContext(bundleName2, moduleName2); + // ... + } } ``` @@ -222,77 +235,90 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - let moduleName2 = "module1"; - let context2 = this.context.createModuleContext(moduleName2); - // ... - } + onCreate(want, launchParam) { + let moduleName2 = 'module1'; + 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 import UIAbility from '@ohos.app.ability.UIAbility'; import window from '@ohos.window'; -const TAG: string = "[Example].[Entry].[EntryAbility]"; +const TAG: string = '[Example].[Entry].[EntryAbility]'; export default class EntryAbility extends UIAbility { - lifecycleId: number; - - onCreate(want, launchParam) { - let abilityLifecycleCallback = { - onAbilityCreate(ability) { - console.info(TAG, "onAbilityCreate ability:" + JSON.stringify(ability)); - }, - onWindowStageCreate(ability, windowStage) { - console.info(TAG, "onWindowStageCreate ability:" + JSON.stringify(ability)); - console.info(TAG, "onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); - }, - onWindowStageActive(ability, windowStage) { - console.info(TAG, "onWindowStageActive ability:" + JSON.stringify(ability)); - console.info(TAG, "onWindowStageActive windowStage:" + JSON.stringify(windowStage)); - }, - onWindowStageInactive(ability, windowStage) { - console.info(TAG, "onWindowStageInactive ability:" + JSON.stringify(ability)); - console.info(TAG, "onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); - }, - onWindowStageDestroy(ability, windowStage) { - console.info(TAG, "onWindowStageDestroy ability:" + JSON.stringify(ability)); - console.info(TAG, "onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); - }, - onAbilityDestroy(ability) { - console.info(TAG, "onAbilityDestroy ability:" + JSON.stringify(ability)); - }, - onAbilityForeground(ability) { - console.info(TAG, "onAbilityForeground ability:" + JSON.stringify(ability)); - }, - onAbilityBackground(ability) { - console.info(TAG, "onAbilityBackground ability:" + JSON.stringify(ability)); - }, - onAbilityContinue(ability) { - console.info(TAG, "onAbilityContinue ability:" + JSON.stringify(ability)); - } - } - // 1. Obtain the application context through the context attribute. - let applicationContext = this.context.getApplicationContext(); - // 2. Register a listener for the lifecycle changes through the application context. - this.lifecycleId = applicationContext.on("abilityLifecycle", abilityLifecycleCallback); - console.info(TAG, "register callback number: " + JSON.stringify(this.lifecycleId)); + // Define a lifecycle ID. + lifecycleId: number; + + onCreate(want, launchParam) { + // Define a lifecycle callback object. + let abilityLifecycleCallback = { + // Called when a UIAbility is created. + onAbilityCreate(uiAbility) { + console.log(TAG, `onAbilityCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + }, + // Called when a window is created. + onWindowStageCreate(uiAbility, windowStage: window.WindowStage) { + console.log(TAG, `onWindowStageCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.log(TAG, `onWindowStageCreate windowStage: ${JSON.stringify(windowStage)}`); + }, + // Called when the window becomes active. + onWindowStageActive(uiAbility, windowStage: window.WindowStage) { + console.log(TAG, `onWindowStageActive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.log(TAG, `onWindowStageActive windowStage: ${JSON.stringify(windowStage)}`); + }, + // Called when the window becomes inactive. + onWindowStageInactive(uiAbility, windowStage: window.WindowStage) { + console.log(TAG, `onWindowStageInactive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.log(TAG, `onWindowStageInactive windowStage: ${JSON.stringify(windowStage)}`); + }, + // Called when the window is destroyed. + onWindowStageDestroy(uiAbility, windowStage: window.WindowStage) { + console.log(TAG, `onWindowStageDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.log(TAG, `onWindowStageDestroy windowStage: ${JSON.stringify(windowStage)}`); + }, + // Called when the UIAbility is destroyed. + onAbilityDestroy(uiAbility) { + console.log(TAG, `onAbilityDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + }, + // Called when the UIAbility is switched from the background to the foreground. + onAbilityForeground(uiAbility) { + console.log(TAG, `onAbilityForeground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + }, + // Called when the UIAbility is switched from the foreground to the background. + onAbilityBackground(uiAbility) { + 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) => { - console.info(TAG, "unregister callback success, err: " + JSON.stringify(error)); - }); - } + // ... + + onDestroy() { + // Obtain the application context. + let applicationContext = this.context.getApplicationContext(); + // Deregister the application lifecycle callback. + applicationContext.off('abilityLifecycle', this.lifecycleId); + } } ``` diff --git a/en/application-dev/application-models/component-startup-rules.md b/en/application-dev/application-models/component-startup-rules.md index 0e6c2ce33c68913221c7b09f02e96327b0ea1c30..26b2446893aea096611f896e878ef15888830afa 100644 --- a/en/application-dev/application-models/component-startup-rules.md +++ b/en/application-dev/application-models/component-startup-rules.md @@ -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. - 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. diff --git a/en/application-dev/application-models/create-pageability.md b/en/application-dev/application-models/create-pageability.md index 783646ff4cfd5fa2ab193005bfa9d182dc75b70c..d33b7af946dd0e935a149ebb11ef1ecbedf05ca8 100644 --- a/en/application-dev/application-models/create-pageability.md +++ b/en/application-dev/application-models/create-pageability.md @@ -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 { @@ -48,13 +48,13 @@ After the PageAbility is created, its abilities-related configuration items are ], "orientation": "unspecified", "visible": true, - "srcPath": "EntryAbility", - "name": ".EntryAbility", + "srcPath": "MainAbility", + "name": ".MainAbility", "srcLanguage": "ets", "icon": "$media:icon", - "description": "$string:EntryAbility_desc", + "description": "$string:MainAbility_desc", "formsEnabled": false, - "label": "$string:EntryAbility_label", + "label": "$string:MainAbility_label", "type": "page", "launchType": "singleton" } @@ -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: ```ts -import featureAbility from '@ohos.ability.featureAbility' -import fileIo from '@ohos.fileio' +import featureAbility from '@ohos.ability.featureAbility'; +import fs from '@ohos.file.fs'; (async () => { - let dir: string + let dir: string; try { - console.info('Begin to getOrCreateDistributedDir') - dir = await featureAbility.getContext().getOrCreateDistributedDir() + console.info('Begin to getOrCreateDistributedDir'); + dir = await featureAbility.getContext().getOrCreateDistributedDir(); console.info('distribute dir is ' + dir) } catch (error) { - console.error('getOrCreateDistributedDir failed with ' + error) + console.error('getOrCreateDistributedDir failed with ' + error); } let fd: number; let path = dir + "/a.txt"; - fd = fileIo.openSync(path, 0o2 | 0o100, 0o666); - fileIo.close(fd); + fd = fs.openSync(path, fs.OpenMode.READ_WRITE).fd; + fs.close(fd); })() ``` diff --git a/en/application-dev/application-models/data-share-via-want.md b/en/application-dev/application-models/data-share-via-want.md index c04bea2916647804b51022cee1853f3b5d0a7d90..05da4e529947cf62a98fa81a4b6ed4578c9e0346 100644 --- a/en/application-dev/application-models/data-share-via-want.md +++ b/en/application-dev/application-models/data-share-via-want.md @@ -1,111 +1,133 @@ # 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. +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 - -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. - -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. - -3. The following actions are involved in this section: - - **ACTION_SELECT (ohos.want.action.select)**: action of displaying the application selector. - - **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. - - -## How to Develop - -- Sharing party - 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. - - ```ts - import fileIO from '@ohos.fileio'; - - // let path = ... - // Open the file whose path is a variable. - let fileFd = fileIO.openSync(path, 0o102, 0o666); - ``` - - 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. - - ```ts - import wantConstant from '@ohos.app.ability.wantConstant'; - - // let path = ... - // let fileFd = ... - // let fileSize = ... - let want = { - / This action is used to implicitly match the application selector. - action: wantConstant.Action.ACTION_SELECT, - // This is the custom parameter in the first layer of Want, - / which is intended to add information to the application selector. - parameters: { - // MIME type of PDF. - "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 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. + +The following actions are involved 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. + +## Sharing 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 + +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**. + +```ts +import common from '@ohos.app.ability.common'; + +let fileType = 'application/pdf'; +let fileName = 'TestFile.pdf'; +let fileFd = -1; // Obtain the file descriptor (FD) of the file to share. +let fileSize; // Obtain the size of the file to share. + +function implicitStartAbility() { + let context = getContext(this) as common.UIAbilityContext; + let wantInfo = { + / This action is used to implicitly match the application sharing box. + action: 'ohos.want.action.select', + // This is the custom parameter in the first layer of Want, + / which is intended to add information to the application sharing box. + parameters: { + // MIME type of PDF. + 'ability.picker.type': fileType, + 'ability.picker.fileNames': [fileName], + 'ability.picker.fileSizes': [fileSize], + // This is 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: - - - **"ability.picker.type"**: The application selector renders the file type icon based on this field. - - **"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: - - ![stage-want2](figures/stage-want2.png) - - 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. - -- 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: - - ```ts - "skills": [ - { - "entities": [ + } + } + context.startAbility(wantInfo).then(() => { + // ... + }).catch((err) => { + // ... + }) +} +``` + +> **NOTE** +> +> 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, under the custom field **parameters**, the following **ability.picker.*** fields are used to pass the information to be displayed on the application sharing box: + +- **ability.picker.type**: file type icon. +- **ability.picker.fileNames**: file name. +- **ability.picker.fileSizes**: file size, in bytes. +- **ability.picker.fileNames** and **ability.picker.fileSizes** are arrays and have a one-to-one mapping. + +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" // ... - ], - "uris": [ - { - "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; - // ... - } + ], + "uris": [ + { + "type": "application/pdf" + }, + ] + } + ] } - ``` + ] + } +} +``` + +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": [] +} +``` diff --git a/en/application-dev/application-models/explicit-implicit-want-mappings.md b/en/application-dev/application-models/explicit-implicit-want-mappings.md index d2c44bb4b47eff6347d6b4a6c098feadb7a9eead..921cdec8ba0cd051292421fba0ecbb2e9f57797e 100644 --- a/en/application-dev/application-models/explicit-implicit-want-mappings.md +++ b/en/application-dev/application-models/explicit-implicit-want-mappings.md @@ -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 - -The table below describes the matching rules of explicit Want. - | Name| Type| Matching Item| Mandatory| Rule Description| | -------- | -------- | -------- | -------- | -------- | | deviceId | string | Yes| No| If this field is unspecified, only abilities on the local device are matched.| @@ -22,8 +19,6 @@ The table below describes the matching rules of explicit Want. ## Matching Rules for Implicit Want -The table below describes the matching rules of implicit Want. - | Name | Type | Matching Item| Mandatory| Rule Description | | ----------- | ------------------------------ | ------ | ---- | ------------------------------------------------------------ | | deviceId | string | Yes | No | Implicit invoking is not supported across devices. | @@ -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.| | parameters | {[key: string]: 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. @@ -50,7 +46,7 @@ The system matches the **want** parameter (including the **action**, **entities* ### 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. @@ -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. - **Figure 1** Matching rules of action in the want parameter - - ![want-action](figures/want-action.png) + **Figure 1** Matching rules of action in the want parameter + + ![want-action](figures/want-action.png) ### 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. @@ -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. - 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 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: - 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 - 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. +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 @@ -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 **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. @@ -139,12 +139,17 @@ To simplify the description, **uri** in the passed **want** parameter is called > **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: +> +> - **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 expression**: `scheme://host:port/pathStartWith` -> -> - **Regular expression**: `scheme://host:port/pathRegex` +> - **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://` +> * `scheme://host` +> * `scheme://host:port` ### Matching Rules of type diff --git a/en/application-dev/application-models/figures/want-uri-type1.png b/en/application-dev/application-models/figures/want-uri-type1.png index e0fe40d1a3cd40b72379bd947aaf2e3977021b32..ed53694a9608e8529c5e4633fca42b041bc7ab76 100644 Binary files a/en/application-dev/application-models/figures/want-uri-type1.png and b/en/application-dev/application-models/figures/want-uri-type1.png differ diff --git a/en/application-dev/application-models/hop-cross-device-migration.md b/en/application-dev/application-models/hop-cross-device-migration.md index d90a10995f0aeba773179fc7807ab25711b4594c..714698d002237cf3c2d45267596089c1317c66af 100644 --- a/en/application-dev/application-models/hop-cross-device-migration.md +++ b/en/application-dev/application-models/hop-cross-device-migration.md @@ -1,4 +1,4 @@ -# Cross-Device Migration (for System Applications Only)] +# Cross-Device Migration (for System Applications Only) ## When to Use diff --git a/en/application-dev/application-models/hop-multi-device-collaboration.md b/en/application-dev/application-models/hop-multi-device-collaboration.md index e5dfb522fcc8ffa05106e87197de6b276e4c9e00..7cf66fbab7a98b109de3f9ffcc2fc7b7a2ecd127 100644 --- a/en/application-dev/application-models/hop-multi-device-collaboration.md +++ b/en/application-dev/application-models/hop-multi-device-collaboration.md @@ -11,7 +11,7 @@ Multi-device coordination involves the following scenarios: - [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 @@ -102,7 +102,7 @@ On device A, touch the **Start** button provided by the initiator application to abilityName: 'FuncAbility', 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(() => { // ... }).catch((err) => { @@ -118,7 +118,7 @@ On device A, touch the **Start** button provided by the initiator application to ### 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| | -------- | -------- | @@ -154,7 +154,7 @@ On device A, touch the **Start** button provided by the initiator application to abilityName: 'FuncAbility', 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) => { // ... }).catch((err) => { @@ -174,7 +174,7 @@ On device A, touch the **Start** button provided by the initiator application to 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) => { // ... }); @@ -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) => { if (data?.resultCode === RESULT_CODE) { // 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 ``` -## 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 -**Table 4** Ability call APIs +**Table 4** Call APIs | API| Description| | -------- | -------- | | startAbilityByCall(want: Want): Promise<Caller>; | 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.| -| off(method: string): void | Callback invoked when the callee ability deregisters a method.| -| call(method: string, data: rpc.Parcelable): Promise<void> | Sends agreed parcelable data to the callee ability.| -| callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence> | Sends agreed parcelable data to the callee ability and obtains the agreed parcelable data returned by the callee ability.| +| on(method: string, callback: CalleeCallBack): void | Callback invoked when the CalleeAbility registers a method.| +| off(method: string): void | Callback invoked when the CalleeAbility deregisters a method.| +| call(method: string, data: rpc.Parcelable): Promise<void> | Sends agreed parcelable data to the CalleeAbility.| +| callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence> | Sends agreed parcelable data to the CalleeAbility and obtains the agreed parcelable data returned by the CalleeAbility.| | release(): void | Releases the caller object.| | 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 } ``` -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. - 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| | -------- | -------- | - | "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: @@ -401,7 +401,7 @@ The following describes how to implement multi-device collaboration through cros 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 export default class MyParcelable { @@ -438,13 +438,13 @@ The following describes how to implement multi-device collaboration through cros function sendMsgCallback(data) { 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, '') data.readParcelable(receivedData) console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) // 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`) } @@ -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. ```ts @@ -476,7 +476,7 @@ The following describes how to implement multi-device collaboration through cros 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 async onButtonGetRemoteCaller() { @@ -491,7 +491,7 @@ The following describes how to implement multi-device collaboration through cros if (data != null) { caller = data console.info('get remote caller success') - // 注册caller的release监听 + // Register the onRelease listener of the CallerAbility. caller.onRelease((msg) => { console.info(`remote caller onRelease is called ${msg}`) }) @@ -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). -5. Sends agreed parcelable data to the callee ability. - 1. The parcelable data can be sent to the callee ability with or without a return value. The method and parcelable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability. +5. Sends agreed parcelable data to the CalleeAbility. + 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 const MSG_SEND_METHOD: string = 'CallSendMsg' @@ -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 const MSG_SEND_METHOD: string = 'CallSendMsg' diff --git a/en/application-dev/application-models/mission-management-overview.md b/en/application-dev/application-models/mission-management-overview.md index b6f6668f7ce56a9de0b5a3d0182b14ec189703c9..e371e8380fbd7e181e13f1d5f5e7487b15eb9ff1 100644 --- a/en/application-dev/application-models/mission-management-overview.md +++ b/en/application-dev/application-models/mission-management-overview.md @@ -28,10 +28,10 @@ Missions are managed by system applications (such as home screen), rather than t - 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: diff --git a/en/application-dev/application-models/uiability-intra-device-interaction.md b/en/application-dev/application-models/uiability-intra-device-interaction.md index 58cea75a988647cbbc3e53e3918990812cfdc702..5ea819219e45d219e68aee7f34988f4822dda5a9 100644 --- a/en/application-dev/application-models/uiability-intra-device-interaction.md +++ b/en/application-dev/application-models/uiability-intra-device-interaction.md @@ -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) -- [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 @@ -38,7 +38,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func 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(() => { // ... }).catch((err) => { @@ -54,7 +54,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func export default class FuncAbility extends UIAbility { onCreate(want, launchParam) { - // Receive the parameters passed by the caller UIAbility. + // Receive the parameters passed by the initiator UIAbility. let funcAbilityWant = want; let info = funcAbilityWant?.parameters?.info; // ... @@ -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. ```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) => { // ... }); @@ -88,7 +88,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned 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) => { // ... }).catch((err) => { @@ -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) => { // ... }); ``` -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 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) => { 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; // ... } @@ -139,13 +139,13 @@ When starting FuncAbility from EntryAbility, you want the result to be returned ## 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). - 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. @@ -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 let wantInfo = { @@ -187,7 +187,7 @@ This section describes how to start the UIAbility of another application through 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(() => { // ... }).catch((err) => { @@ -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()**. ```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) => { // ... }); @@ -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 -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**. @@ -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 let wantInfo = { @@ -251,7 +251,7 @@ If you want to obtain the return result when using implicit Want to start the UI 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) => { // ... }).catch((err) => { @@ -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 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 }, }, } - // context is the ability-level context of the callee UIAbility. + // context is the AbilityContext of the target UIAbility. 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 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 // 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) => { 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; // ... } @@ -309,7 +309,7 @@ A UIAbility component can have multiple pages. When it is started in different s ### 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 @@ -322,7 +322,7 @@ let wantInfo = { 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(() => { // ... }).catch((err) => { @@ -344,12 +344,12 @@ export default class FuncAbility extends UIAbility { funcAbilityWant; onCreate(want, launchParam) { - // Receive the parameters passed by the caller UIAbility. + // Receive the parameters passed by the initiator UIAbility. this.funcAbilityWant = want; } 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'; if (this.funcAbilityWant?.parameters?.router) { if (this.funcAbilityWant.parameters.router === 'funA') { @@ -379,7 +379,7 @@ In summary, when a UIAbility instance of application A has been created and the export default class FuncAbility extends UIAbility { onNewWant(want, launchParam) { - // Receive the parameters passed by the caller UIAbility. + // Receive the parameters passed by the initiator UIAbility. globalThis.funcAbilityWant = want; // ... } @@ -412,81 +412,83 @@ In summary, when a UIAbility instance of application A has been created and the ``` > **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| | -------- | -------- | -| CallerAbility | UIAbility that triggers the ability call.| -| CalleeAbility | UIAbility invoked by the ability call.| -| Caller | Object returned by **startAbilityByCall** and used by the caller ability to communicate with the callee ability.| -| Callee | Object held by the callee ability to communicate with the caller ability.| +| CallerAbility | UIAbility that triggers the call.| +| CalleeAbility | UIAbility invoked by the call.| +| Caller | Object returned by **startAbilityByCall** and used by the CallerAbility to communicate with the CalleeAbility.| +| 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) -- 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** -> 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 -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| | -------- | -------- | | startAbilityByCall(want: Want): Promise<Caller> | 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.| -| off(method: string): void | Callback invoked when the callee ability deregisters a method.| -| call(method: string, data: rpc.Parcelable): Promise<void> | Sends agreed parcelable data to the callee ability.| -| callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence> | Sends agreed parcelable data to the callee ability and obtains the agreed parcelable data returned by the callee ability.| +| on(method: string, callback: CalleeCallBack): void | Callback invoked when the CalleeAbility registers a method.| +| off(method: string): void | Callback invoked when the CalleeAbility deregisters a method.| +| call(method: string, data: rpc.Parcelable): Promise<void> | Sends agreed parcelable data to the CalleeAbility.| +| callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence> | Sends agreed parcelable data to the CalleeAbility and obtains the agreed parcelable data returned by the CalleeAbility.| | release(): void | Releases the caller object.| | 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. - Set **launchType** of the callee ability to **singleton** in the **module.json5** file. +1. Configure the launch type of the UIAbility. + + Set **launchType** of the CalleeAbility to **singleton** in the **module.json5** file. | JSON Field| Description| | -------- | -------- | @@ -514,7 +516,8 @@ For the callee ability, implement the callback to receive data and the methods t ``` 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 @@ -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**. - 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 @@ -552,13 +556,13 @@ For the callee ability, implement the callback to receive data and the methods t function sendMsgCallback(data) { 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, ''); data.readParcelable(receivedData); console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); // 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`); } @@ -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. @@ -591,11 +595,12 @@ For the callee ability, implement the callback to receive data and the methods t ``` 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 - // Register the onRelease() listener of the caller ability. + // Register the onRelease() listener of the CallerAbility. private regOnRelease(caller) { try { caller.on("release", (msg) => { diff --git a/en/application-dev/application-models/uiability-launch-type.md b/en/application-dev/application-models/uiability-launch-type.md index 19d7b73402e354027c1ff72ff4c2432dc56f8862..cf185cd9dad9593534afef59babe5cbf37585cae 100644 --- a/en/application-dev/application-models/uiability-launch-type.md +++ b/en/application-dev/application-models/uiability-launch-type.md @@ -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) -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 { @@ -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. - 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. +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. ```ts // Configure an independent key for each UIAbility instance. @@ -114,7 +113,7 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of 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(() => { // ... }).catch((err) => { @@ -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 this example, SpecifiedAbility of module1 is returned. 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}`; } @@ -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. > 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. - 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. - 4. Return to the home screen and open file A again. UIAbility instance 2 is started. \ No newline at end of file