diff --git a/en/application-dev/application-models/Readme-EN.md b/en/application-dev/application-models/Readme-EN.md index 05cdc41e5d2027e9e3bfba373ed14916b3e790a1..cac37cb7a7714579497854fa0e6110ee65b8ee4d 100644 --- a/en/application-dev/application-models/Readme-EN.md +++ b/en/application-dev/application-models/Readme-EN.md @@ -20,7 +20,7 @@ - [AccessibilityExtensionAbility](accessibilityextensionability.md) - [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md) - [InputMethodExtensionAbility](inputmethodextentionability.md) - - [WindowExtensionAbility](windowextensionability.md) + - [WindowExtensionAbility (for System Applications Only)](windowextensionability.md) - Service Widget Development in Stage Model - [Service Widget Overview](service-widget-overview.md) - Developing an ArkTS Widget @@ -52,7 +52,7 @@ - [Want Overview](want-overview.md) - [Matching Rules of Explicit Want and Implicit Want](explicit-implicit-want-mappings.md) - [Common action and entities Values](actions-entities.md) - - [Using Explicit Want to Start an Ability](ability-startup-with-explicit-want.md) + - [Using Explicit Want to Start an Application Component](ability-startup-with-explicit-want.md) - [Using Implicit Want to Open a Website](ability-startup-with-implicit-want.md) - [Using Want to Share Data Between Applications](data-share-via-want.md) - [Component Startup Rules](component-startup-rules.md) @@ -78,10 +78,10 @@ - [Using Worker for Inter-Thread Communication](itc-with-worker.md) - Mission Management - [Mission Management Scenarios](mission-management-overview.md) - - [Mission Management and Launch Type](mission-management-launch-type.md) + - [Mission and Launch Type](mission-management-launch-type.md) - [Page Stack and MissionList](page-mission-stack.md) - [Setting the Icon and Name of a Mission Snapshot](mission-set-icon-name-for-task-snapshot.md) - - [Application Configuration File (Stage Model)](config-file-stage.md) + - [Application Configuration File](config-file-stage.md) - FA Model Development - [FA Model Development Overview](fa-model-development-overview.md) - FA Mode Application Components 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 80b96ce801bed7d8ae79aa2b3ddc566f10fc2bcf..36d41c555bd8d4a5cd0d4d0b7bd291bb2569cee3 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,5 +1,7 @@ -# Using Explicit Want to Start an Ability +# Using Explicit Want to Start an Application Component -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. If the **abilityName** and **bundleName** parameters are specified when starting a UIAbility, then the explicit Want is used. + +## Using Explicit Want The user touches a button in the application to start the UIAbility component to complete a specific task. To start the UIAbility component in explicit Want mode, the **abilityName** and **bundleName** parameters must be specified. For details, see [Starting UIAbility in the Same Application](uiability-intra-device-interaction.md#starting-uiability-in-the-same-application). 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 e3c94b2963e73aaa896eb5691a2af1932aba7d3c..1f3732b00d6b0a9446d18b4c45019f0820f21be4 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 @@ -5,21 +5,21 @@ This section uses the operation of using a browser to open a website as an examp ```json { "module": { - // ... + ... "abilities": [ { - // ... + ... "skills": [ { "entities": [ "entity.system.home", "entity.system.browsable" - // ... + ... ], "actions": [ "action.system.home", "ohos.want.action.viewData" - // ... + ... ], "uris": [ { @@ -31,9 +31,9 @@ This section uses the operation of using a browser to open a website as an examp }, { "scheme": "http", - // ... + ... } - // ... + ... ] } ] @@ -59,20 +59,19 @@ function implicitStartAbility() { 'uri': 'https://www.test.com:8080/query/student' } context.startAbility(wantInfo).then(() => { - // ... + ... }).catch((err) => { - // ... + ... }) } ``` The matching process is as follows: -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. +1. If **action** in the passed **want** parameter is specified and is included in **actions** under **skills** of the application component 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 application component to match, the matching is successful. +3. If **uri** in the passed **want** parameter is included in **uris** under **skills** of the application component to match, which is concatenated into https://www.test.com:8080/query* (where * is a wildcard), the matching is successful. -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. +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) +![](figures/ability-startup-with-implicit-want1.png) \ No newline at end of file diff --git a/en/application-dev/application-models/abilitystage.md b/en/application-dev/application-models/abilitystage.md index 2f44f69d5810bbddf8128777f63360a1cb196fa3..da764a445a6d1a79a601719f069798191641a986 100644 --- a/en/application-dev/application-models/abilitystage.md +++ b/en/application-dev/application-models/abilitystage.md @@ -24,20 +24,20 @@ AbilityStage is not automatically generated in the default project of DevEco Stu // When the HAP of the application is loaded for the first time, initialize the module. } onAcceptWant(want) { - // Triggered only for the ability with the specified launch type. + // Triggered only for the UIAbility with the specified launch type. return "MyAbilityStage"; } } ``` -4. Set **srcEntry** in the [module.json5 file](../quick-start/module-configuration-file.md) to the code path of the module. +4. In the [module.json5 file](../quick-start/module-configuration-file.md), set **srcEntry** to specify the code path of the module as the entry for loading the HAP. ```json { "module": { "name": "entry", "type": "entry", "srcEntry": "./ets/myabilitystage/MyAbilityStage.ts", - // ... + ... } } ``` diff --git a/en/application-dev/application-models/actions-entities.md b/en/application-dev/application-models/actions-entities.md index 85dfb9523ca117e691480bcbd2321b5fb3b22304..38119a1b1fe16067f7e89629811327ad079a5d15 100644 --- a/en/application-dev/application-models/actions-entities.md +++ b/en/application-dev/application-models/actions-entities.md @@ -1,9 +1,8 @@ # Common action and entities Values -The [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) field specifies the common operation (such as viewing, sharing, and application details) to be performed by the caller. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data, for example, viewing URI data. For example, if the URI is a website and the action is **ohos.want.action.viewData**, the ability that supports website viewing is matched. Declaring the **action** field in Want indicates that the invoked application should support the declared operation. The **actions** field under **skills** in the configuration file indicates the operations supported by the application. +The **action** field specifies the common operation (such as viewing, sharing, and application details) to be performed by the caller. In implicit [Want](../reference/apis/js-apis-app-ability-want.md), you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data, for example, viewing URI data. For example, if the URI is a website and the action is **ohos.want.action.viewData**, the application component that supports website viewing is matched. Declaring the **action** field in [Want](../reference/apis/js-apis-app-ability-want.md) indicates that the invoked application is expected to support the declared operation. The **actions** field under **skills** in the configuration file indicates the operations supported by the application. - -**Common action Values** +The following **action** values are available: - **ACTION_HOME**: action of starting the application entry component. It must be used together with **ENTITY_HOME**. The application icon on the home screen is an explicit entry component. Users can touch the icon to start the entry component. Multiple entry components can be configured for an application. @@ -14,14 +13,13 @@ The [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantactio - **ACTION_VIEW_MULTIPLE_DATA**: action of launching the UI for sending multiple data records. -The [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) field specifies the additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want. You can define this field to filter application categories, for example, browser. Declaring the **entities** field in Want indicates that the invoked application should belong to the declared category. The **entities** field under **skills** in the configuration file indicates the categories supported by the application. - +The **entities** field specify the category information (such as browser and video player) of the target application component. It is a supplement to **action** in implicit Want. You can define this field to filter application categories, for example, browser. Declaring the **entities** field in Want indicates that the invoked application should belong to the declared category. The **entities** field under **skills** in the configuration file indicates the categories supported by the application. -**Common entities Values** +The following **entities** values are available: - **ENTITY_DEFAULT**: default category, which is meaningless. -- **ENTITY_HOME**: abilities with an icon displayed on the home screen. +- **ENTITY_HOME**: application components with an icon displayed on the home screen. - **ENTITY_BROWSABLE**: browser type. diff --git a/en/application-dev/application-models/app-deviceconfig-switch.md b/en/application-dev/application-models/app-deviceconfig-switch.md index 1092c21081cd9a8d62c92a1a68ba434efee7c8c9..6c872f0c167bd4779516d611ee07d9036ca550ee 100644 --- a/en/application-dev/application-models/app-deviceconfig-switch.md +++ b/en/application-dev/application-models/app-deviceconfig-switch.md @@ -22,7 +22,7 @@ OpenHarmony has reconstructed the [deviceConfig](../quick-start/deviceconfig-str | deviceConfig in the FA Model| Description| Stage Model| Difference| | -------- | -------- | -------- | -------- | | deviceConfig| Device information.| / | This tag is no longer available in the stage model. In the stage model, device information is configured under the **app** tag.| -| process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process.| / | The stage model does not support the configuration of process names.| +| process | Name of the process running the application or UIAbility. If the **process** attribute is configured in the **deviceConfig** tag, all UIAbilities of the application run in this process. You can set the **process** attribute for a specific UIAbility in the **abilities** attribute, so that the UIAbility can run in the particular process.| / | The stage model does not support the configuration of process names.| | keepAlive | Whether the application is always running. This attribute applies only to system applications and does not take effect for third-party applications.| / | The stage model does not support changing of the model control mode for system applications.| | supportBackup | Whether the application supports data backup and restore.| / | This configuration is not supported in the stage model.| | compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed.| / | This configuration is not supported in the stage model.| diff --git a/en/application-dev/application-models/application-component-configuration-fa.md b/en/application-dev/application-models/application-component-configuration-fa.md index 4cc1c9ad6831f0e54ae4c70f4f7229a7abc7c62f..336ad698d0f2298045b00fe0af1563574bccfd24 100644 --- a/en/application-dev/application-models/application-component-configuration-fa.md +++ b/en/application-dev/application-models/application-component-configuration-fa.md @@ -22,7 +22,7 @@ When developing an application, you may need to configure certain tags to identi "actions": ["action.system.home"] } ] - // ... + ... } ``` diff --git a/en/application-dev/application-models/application-component-configuration-stage.md b/en/application-dev/application-models/application-component-configuration-stage.md index bcf9b095464ba0110c35be9cfef44b078a091ffb..b50d40b4a694ecdf55338d249a20ff458d36ba20 100644 --- a/en/application-dev/application-models/application-component-configuration-stage.md +++ b/en/application-dev/application-models/application-component-configuration-stage.md @@ -1,10 +1,12 @@ # Application- or Component-Level Configuration (Stage Model) +When developing an application, you may need to configure certain tags to identify the application, such as the bundle name and application icon. This topic describes key tags that need to be configured during application development. -When developing an application, you may need to configure certain tags to identify the application, such as the bundle name and application icon. This topic describes key tags that need to be configured during application development. Icons and labels are usually configured together. There is the application icon, application label, entry icon, and entry label, which correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). The application icon and label are used in **Settings**. For example, they are displayed in the application list in **Settings**. The entry icon is displayed on the device's home screen after the application is installed. The entry icon maps to a [UIAbility](uiability-overview.md) component. Therefore, an application can have multiple entry icons and labels. When you touch one of them, the corresponding UIAbility page is displayed. +Icons and labels are usually configured together. There is the application icon, application label, entry icon, and entry label, which correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). +The application icon and label are used in **Settings**. For example, they are displayed in the application list in **Settings**. The entry icon is displayed on the device's home screen after the application is installed. The entry icon maps to a [UIAbility](uiability-overview.md) component. Therefore, an application can have multiple entry icons and entry labels. When you touch one of them, the corresponding UIAbility page is displayed. - **Figure 1** Icons and labels +**Figure 1** Icons and labels ![application-component-configuration-stage](figures/application-component-configuration-stage.png) @@ -22,13 +24,13 @@ When developing an application, you may need to configure certain tags to identi The application label is specified by the **label** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** module of the project. The **label** field specifies the application name displayed to users. It must be set to the index of a string resource. ```json - { - "app": { - "icon": "$media:app_icon", - "label": "$string:app_name" - // ... - } + { + "app": { + "icon": "$media:app_icon", + "label": "$string:app_name" + ... } + } ``` - **Configuring the entry icon and label** @@ -40,7 +42,7 @@ When developing an application, you may need to configure certain tags to identi ```json { "module": { - // ... + ... "abilities": [ { // The information starting with $ is the resource value. @@ -61,6 +63,35 @@ When developing an application, you may need to configure certain tags to identi } } ``` + OpenHarmony strictly controls applications without icons to prevent malicious applications from deliberately configuring no icon to block uninstall attempts. + + To hide an application icon from the home screen, you must configure the **AllowAppDesktopIconHide** privilege. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). The rules for displaying the entry icon and entry label are as follows: + + 1. The HAP file contains UIAbility configuration. + * An entry icon is set in the **abilities** field of the **module.json5** file. + * The application does not have the privilege to hide its icon from the home screen. + * The system uses the icon configured for the UIAbility as the entry icon and displays it on the home screen. Touching this icon will direct the user to the home page of the UIAbility. + * The system uses the label configured for the UIAbility as the entry label and displays it on the home screen. If no label is configured, the system uses the label specified in the **app.json5** file as the entry label and displays it on the home screen. + * The application has the privilege to hide its icon from the home screen. + * The application information is not returned when the home screen queries the information, and the entry icon and label of the application are not displayed on the home screen. + * No entry icon is set in the **abilities** field of the **module.json5** file. + * The application does not have the privilege to hide its icon from the home screen. + * The system uses the icon specified in the **app.json5** file as the entry icon and displays it on the home screen. Touching this icon will direct the user to the application details page, as shown below. + * The system uses the label specified in the **app.json5** file as the entry label and displays it on the home screen. + * The application has the privilege to hide its icon from the home screen. + * The application information is not returned when the home screen queries the information, and the entry icon and label of the application are not displayed on the home screen. + + 2. The HAP file does not contain UIAbility configuration. + * The application does not have the privilege to hide its icon from the home screen. + * The system uses the icon specified in the **app.json5** file as the entry icon and displays it on the home screen. Touching this icon will direct the user to the application details page, as shown below. + * The system uses the label specified in the **app.json5** file as the entry label and displays it on the home screen. + * The application has the privilege to hide its icon from the home screen. + * The application information is not returned when the home screen queries the information, and the entry icon and label of the application are not displayed on the home screen. + + **Figure 2** Application details page + + ![Application details page](figures/application_details.jpg) + - **Configuring application version declaration** To declare the application version, configure the **versionCode** and **versionName** fields in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. **versionCode** specifies the version number of the application. The value is a 32-bit non-negative integer. It is used only to determine whether a version is later than another version. A larger value indicates a later version. **versionName** provides the text description of the version number. diff --git a/en/application-dev/application-models/application-context-stage.md b/en/application-dev/application-models/application-context-stage.md index e009f360037580700cc6fe2c74a80db3f899a504..2063eee286c25e360a1700d3e1771d865b875f1c 100644 --- a/en/application-dev/application-models/application-context-stage.md +++ b/en/application-dev/application-models/application-context-stage.md @@ -1,19 +1,16 @@ # Context (Stage Model) - ## Overview [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 level). 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. +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 an application component, obtain the application component configuration, and more. ```ts @@ -21,7 +18,7 @@ export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let uiAbilityContext = this.context; - // ... + ... } } ``` @@ -36,7 +33,7 @@ export default class MyService extends ServiceExtensionAbility { onCreate(want) { let serviceExtensionContext = this.context; - // ... + ... } } ``` @@ -47,7 +44,7 @@ export default class MyAbilityStage extends AbilityStage { onCreate() { let abilityStageContext = this.context; - // ... + ... } } ``` @@ -58,7 +55,7 @@ export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let applicationContext = this.context.getApplicationContext(); - // ... + ... } } ``` @@ -85,12 +82,12 @@ The following table describes the application development paths obtained from co | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | 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.| +| cacheDir | string | Yes| No| Path for storing the 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 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 preference files, that is, preferences directory of the application. | +| tempDir | string | Yes | No | Path for storing the 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.| +| distributedFilesDir | string | Yes| No| Path for storing the 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. @@ -135,7 +132,7 @@ export default class EntryAbility extends UIAbility { let bundleCodeDir = this.context.bundleCodeDir; let distributedFilesDir = this.context.distributedFilesDir; let preferencesDir = this.context.preferencesDir; - // ... + ... } } ``` @@ -148,7 +145,7 @@ export default class EntryAbility extends UIAbility { 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 a directory with the device-level encryption (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 a directory with the user-level encryption (EL2). -In practice, you need to select a proper encrypted level based on scenario-specific requirements to protect application data security. The proper use of EL1 and the EL2 can efficiently improve the security. +In practice, you need to select a proper encryption level based on scenario-specific requirements to protect application data security. The proper use of EL1 and the EL2 can efficiently improve the security. > **NOTE** > @@ -187,13 +184,13 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../ > **NOTE** > > To obtain the context of another application: - > + > > - 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'; @@ -202,7 +199,7 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../ let bundleName2 = 'com.example.application'; let context2 = this.context.createBundleContext(bundleName2); let label2 = context2.applicationInfo.label; - // ... + ... } } ``` @@ -224,7 +221,7 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../ let bundleName2 = 'com.example.application'; let moduleName2 = 'module1'; let context2 = this.context.createModuleContext(bundleName2, moduleName2); - // ... + ... } } ``` @@ -238,7 +235,7 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../ onCreate(want, launchParam) { let moduleName2 = 'module1'; let context2 = this.context.createModuleContext(moduleName2); - // ... + ... } } ``` @@ -266,53 +263,53 @@ export default class EntryAbility extends UIAbility { let abilityLifecycleCallback = { // Called when a UIAbility is created. onAbilityCreate(uiAbility) { - console.log(TAG, `onAbilityCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(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)}`); + console.info(TAG, `onWindowStageCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(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)}`); + console.info(TAG, `onWindowStageActive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(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)}`); + console.info(TAG, `onWindowStageInactive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(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)}`); + console.info(TAG, `onWindowStageDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onWindowStageDestroy windowStage: ${JSON.stringify(windowStage)}`); }, // Called when the UIAbility is destroyed. onAbilityDestroy(uiAbility) { - console.log(TAG, `onAbilityDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(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)}`); + console.info(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)}`); + console.info(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)}`); + console.info(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('abilityLifecycle', abilityLifecycleCallback); - console.log(TAG, `register callback number: ${this.lifecycleId}`); + console.info(TAG, `register callback number: ${this.lifecycleId}`); } - // ... + ... onDestroy() { // Obtain the application context. diff --git a/en/application-dev/application-models/application-model-description.md b/en/application-dev/application-models/application-model-description.md index 0cdfa7323c6ef367a47a44e2c30104d3201ca159..20fa9019d10c8d242e34b309debec78e722e6c27 100644 --- a/en/application-dev/application-models/application-model-description.md +++ b/en/application-dev/application-models/application-model-description.md @@ -12,10 +12,9 @@ Along its evolution, OpenHarmony has provided two application models: The stage model is designed based on the following considerations, which make it become the recommended model: 1. **Designed for complex applications** - - In the stage model, multiple application components share an ArkTS engine (VM running the programming language ArkTS) instance, making it easy for application components to share objects and status while requiring less memory. - The object-oriented development mode makes the code of complex applications easy to read, maintain, and scale. - + 2. **Native support for [cross-device migration](hop-cross-device-migration.md) and [multi-device collaboration](hop-multi-device-collaboration.md) at the application component level** The stage model decouples application components from User Interfaces (UIs). @@ -38,7 +37,7 @@ The stage model is designed based on the following considerations, which make it The stage model redefines the boundary of application capabilities to well balance application capabilities and system management costs. - - Diverse application components (such as widgets and input methods) for specific scenarios. + - Diverse application components (such as service widgets and input methods) for specific scenarios. - Standardized background process management. To deliver a better user experience, the stage model manages background application processes in a more orderly manner. Applications cannot reside in the background randomly, and their background behavior is strictly managed to minimize malicious behavior. @@ -52,8 +51,8 @@ The table below describes their differences in detail. | Item| FA model| Stage model| | -------- | -------- | -------- | -| **Application component**| 1. Component classification
![fa-model-component](figures/fa-model-component.png)
- PageAbility: has the UI and supports user interaction For details, see [PageAbility Component Overview](pageability-overview.md).
- ServiceAbility: provides background services and has no UI. For details, see [ServiceAbility Component Overview](serviceability-overview.md).
- DataAbility: provides the data sharing capability and has no UI. For details, see [DataAbility Component Overview](dataability-overview.md).
2. Development mode
Application components are specified by exporting anonymous objects and fixed entry files. You cannot perform derivation. It is inconvenient for capability expansion. | 1. Component classification
![stage-model-component](figures/stage-model-component.png)
- UIAbility: has the UI and supports user interaction. For details, see [UIAbility Component Overview](uiability-overview.md).
- ExtensionAbility: provides extension capabilities (such as widget and input methods) for specific scenarios. For details, see [ExtensionAbility Component Overview](extensionability-overview.md).
2. Development mode
The object-oriented mode is used to provide open application components as classes. You can derive application components for capability expansion. | -| **Process model**| There are two types of processes:
1. Main process
2. Rendering process
For details, see [Process Model (FA Model)](process-model-fa.md).| There are three types of processes:
1. Main process
2. ExtensionAbility process
3. Rendering process
For details, see [Process Model (Stage Model)](process-model-stage.md).| -| **Thread model**| 1. ArkTS engine instance creation
A process can run multiple application component instances, and each application component instance runs in an independent ArkTS engine instance.
2. Thread model
Each ArkTS engine instance is created on an independent thread (non-main thread). The main thread does not have an ArkTS engine instance.
3. Intra-process object sharing: not supported.
For details, see [Thread Model (FA Model)](thread-model-fa.md).| 1. ArkTS engine instance creation
A process can run multiple application component instances, and all application component instances share one ArkTS engine instance.
2. Thread model
The ArkTS engine instance is created on the main thread.
3. Intra-process object sharing: supported.
For details, see [Thread Model (Stage Model)](thread-model-stage.md).| +| **Application component**| 1. Component classification
![fa-model-component](figures/fa-model-component.png)
- PageAbility: has the UI and supports user interaction For details, see [PageAbility Component Overview](pageability-overview.md).
- ServiceAbility: provides background services and has no UI. For details, see [ServiceAbility Component Overview](serviceability-overview.md).
- DataAbility: provides the data sharing capability and has no UI. For details, see [DataAbility Component Overview](dataability-overview.md).
2. Development mode
Application components are specified by exporting anonymous objects and fixed entry files. You cannot perform derivation. It is inconvenient for capability expansion.| 1. Component classification
![stage-model-component](figures/stage-model-component.png)
- UIAbility: has the UI and supports user interaction. For details, see [UIAbility Component Overview](uiability-overview.md).
- ExtensionAbility: provides extension capabilities (such as widget and input methods) for specific scenarios. For details, see [ExtensionAbility Component Overview](extensionability-overview.md).
2. Development mode
The object-oriented mode is used to provide open application components as classes. You can derive application components for capability expansion.| +| **Process model**| There are two types of processes:
1. Main process
2. Rendering process
For details, see [Process Model Overview (FA Model)](process-model-fa.md). | There are three types of processes:
1. Main process
2. ExtensionAbility process
3. Rendering process
For details, see [Process Model Overview (Stage Model)](process-model-stage.md). | +| **Thread model**| 1. ArkTS engine instance creation
A process can run multiple application component instances, and each application component instance runs in an independent ArkTS engine instance.
2. Thread model
Each ArkTS engine instance is created on an independent thread (non-main thread). The main thread does not have an ArkTS engine instance.
3. Intra-process object sharing: not supported.
For details, see [Thread Model Overview (FA Model)](thread-model-fa.md). | 1. ArkTS engine instance creation
A process can run multiple application component instances, and all application component instances share one ArkTS engine instance.
2. Thread model
The ArkTS engine instance is created on the main thread.
3. Intra-process object sharing: supported.
For details, see [Thread Model Overview (Stage Model)](thread-model-stage.md). | | **Mission management model**| - A mission is created for each PageAbility component instance.
- Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions.
- PageAbility components do not form a stack structure.
For details, see [Mission Management Scenarios](mission-management-overview.md).| - A mission is created for each UIAbility component instance.
- Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions.
- UIAbility components do not form a stack structure.
For details, see [Mission Management Scenarios](mission-management-overview.md).| | **Application configuration file**| The **config.json** file is used to describe the application, HAP, and application component information.
For details, see [Application Configuration File Overview (FA Model)](../quick-start/application-configuration-file-overview-fa.md).| The **app.json5** file is used to describe the application information, and the **module.json5** file is used to describe the HAP and application component information.
For details, see [Application Configuration File Overview (Stage Model)](../quick-start/application-configuration-file-overview-stage.md).| diff --git a/en/application-dev/application-models/component-startup-rules.md b/en/application-dev/application-models/component-startup-rules.md index 26b2446893aea096611f896e878ef15888830afa..bddf63dbc69ea243733e6f60f67f92a854833bf7 100644 --- a/en/application-dev/application-models/component-startup-rules.md +++ b/en/application-dev/application-models/component-startup-rules.md @@ -23,8 +23,8 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol - **Before starting a component of another application, verify the visible field of the target component.** - - If the **visible** field of the target component is **false**, verify the **ohos.permission.START_INVISIBLE_ABILITY** permission. - - For details, see [Component Visible Configuration](../quick-start/module-configuration-file.md#abilities). + - If the **exported** field of the target component is **false**, verify the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details, see [Component exported Configuration](../quick-start/module-configuration-file.md#abilities). - **Before starting a component of a background application, verify the BACKGROUND permission.** - An application is considered as a foreground application only when the application process gains focus or its UIAbility component is running in the foreground. @@ -37,8 +37,8 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol > **NOTE** > > - Component startup control has been implemented since OpenHarmony v3.2 Release. -> -> - The new component startup rules are more strict than the original ones. You must be familiar with the new startup rules to prevent service exceptions. +> +> - The new component startup rules are more strict than the original ones. You must be familiar with the new startup rules to prevent service exceptions. ## Intra-Device Component Startup Rules diff --git a/en/application-dev/application-models/create-pageability.md b/en/application-dev/application-models/create-pageability.md index d33b7af946dd0e935a149ebb11ef1ecbedf05ca8..d0f308ebc08e035d5568ee0e127a9739e400d124 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 MainAbility: +After the PageAbility is created, its abilities-related configuration items are displayed in the **config.json** file. The following is an example **config.json** file of an ability named EntryAbility: ```json { @@ -48,13 +48,13 @@ After the PageAbility is created, its abilities-related configuration items are ], "orientation": "unspecified", "visible": true, - "srcPath": "MainAbility", - "name": ".MainAbility", + "srcPath": "EntryAbility", + "name": ".EntryAbility", "srcLanguage": "ets", "icon": "$media:icon", - "description": "$string:MainAbility_desc", + "description": "$string:EntryAbility_desc", "formsEnabled": false, - "label": "$string:MainAbility_label", + "label": "$string:EntryAbility_label", "type": "page", "launchType": "singleton" } 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 05da4e529947cf62a98fa81a4b6ed4578c9e0346..28184edbc9304e7c6fbfbfe673cf1b8deca7d635 100644 --- a/en/application-dev/application-models/data-share-via-want.md +++ b/en/application-dev/application-models/data-share-via-want.md @@ -48,9 +48,9 @@ function implicitStartAbility() { } } context.startAbility(wantInfo).then(() => { - // ... + ... }).catch((err) => { - // ... + ... }) } ``` @@ -66,9 +66,8 @@ In the preceding code, under the custom field **parameters**, the following **ab - **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) +The following figure shows an example. +![](figures/ability-startup-with-implicit-want2.png) ## Shared Party @@ -77,17 +76,17 @@ To enable the shared party to identify the shared content, configure **skills** ```json { "module": { - // ... + ... "abilities": [ { - // ... + ... "skills": [ { - // ... + ... "actions": [ "action.system.home", "ohos.want.action.sendData" - // ... + ... ], "uris": [ { @@ -102,7 +101,7 @@ To enable the shared party to identify the shared content, configure **skills** } ``` -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. +After the user selects an application, the Want nested in the **ability.want.params.INTENT** field is passed to that application. After the UIAbility of the application starts, the application obtains **want** information from [**onCreate()**](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [**onNewWant()**](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant). The following is an example of the Want obtained. You can use the FD of the shared file to perform required operations. 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 b0d98063c24ae630d2e26b8067f6cddddfeff57b..454fc89d718fb4adfe84c0eab67ebc332117ed26 100644 --- a/en/application-dev/application-models/explicit-implicit-want-mappings.md +++ b/en/application-dev/application-models/explicit-implicit-want-mappings.md @@ -1,23 +1,28 @@ # Matching Rules of Explicit Want and Implicit Want -Both explicit Want and implicit Want can be used to match an ability to start based on certain rules. These rules determine how the parameters set in Want match the configuration file declared by the target ability. +Both explicit [Want](../reference/apis/js-apis-app-ability-want.md) and implicit [Want](../reference/apis/js-apis-app-ability-want.md) can be used to match an application component to start based on certain rules. These rules determine how the parameters set in [want](../reference/apis/js-apis-app-ability-want.md) match the configuration file declared by the target application component. ## Matching Rules of Explicit Want + +The table below describes the matching rules of explicit [Want](../reference/apis/js-apis-app-ability-want.md). + | Name| Type| Matching Item| Mandatory| Rule Description| | -------- | -------- | -------- | -------- | -------- | -| deviceId | string | Yes| No| If this field is unspecified, only abilities on the local device are matched.| +| deviceId | string | Yes| No| If this field is unspecified, only application components on the local device are matched.| | bundleName | string | Yes| Yes| If **abilityName** is specified but **bundleName** is unspecified, the matching fails.| -| moduleName | string | Yes| No| If this field is unspecified and multiple modules with the same ability name exist in the application, the first ability is matched by default.| +| moduleName | string | Yes| No| If this field is unspecified and multiple modules with the same ability name exist in the application, the first application component is matched by default.| | abilityName | string | Yes| Yes| To use explicit Want, this field must be specified.| -| uri | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| -| type | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| -| action | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| -| entities | Array<string> | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| +| uri | string | No| No| This field is not used for matching. It is passed to the target application component as a parameter.| +| type | string | No| No| This field is not used for matching. It is passed to the target application component as a parameter.| +| action | string | No| No| This field is not used for matching. It is passed to the target application component as a parameter.| +| entities | Array<string> | No| No| This field is not used for matching. It is passed to the target application component as a parameter.| | flags | number | No| No| This field is not used for matching and is directly transferred to the system for processing. It is generally used to set runtime information, such as URI data authorization.| -| parameters | {[key: string]: any} | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| +| parameters | {[key: string]: any} | No| No| This field is not used for matching. It is passed to the target application component as a parameter.| + +## Matching Rules for Implicit Want -## Matching Rules of Implicit Want +The table below describes the matching rules of implicit [Want](../reference/apis/js-apis-app-ability-want.md). | Name | Type | Matching Item| Mandatory| Rule Description | | ----------- | ------------------------------ | ------ | ---- | ------------------------------------------------------------ | @@ -30,31 +35,32 @@ Both explicit Want and implicit Want can be used to match an ability to start ba | action | string | Yes | No | | | entities | Array<string> | Yes | No | | | flags | number | No | No | This field is not used for matching and is directly transferred to the system for processing. It is generally used to set runtime information, such as URI data authorization.| -| parameters | {[key: string]: any} | No | No | This field is not used for matching. It is passed to the target ability as a parameter. | +| parameters | {[key: string]: any} | No | No | This field is not used for matching. It is passed to the target application component as a parameter. | - -## Interpretation of Implicit Want Matching Rules Get familiar with the following about implicit Want: + - The **want** parameter passed by the caller indicates the operation to be performed by the caller. It also provides data and application type restrictions. -- The **skills** field declares the capabilities of the target ability. For details, see [the skills tag](../quick-start/module-configuration-file.md#skills) in the [module.json5 file](../quick-start/module-configuration-file.md). +- The **skills** field declares the capabilities of the target application component. For details, see [the skills tag](../quick-start/module-configuration-file.md#skills) in the [module.json5 file](../quick-start/module-configuration-file.md). -The system matches the **want** parameter (including the **action**, **entities**, **uri**, and **type** attributes) passed by the caller against the **skills** configuration (including the **actions**, **entities**, **uris**, and **type** attributes) of the abilities one by one. When all the four attributes are matched, a dialog box is displayed for users to select a matched application. +The system matches the **want** parameter (including the **action**, **entities**, **uri**, and **type** attributes) passed by the caller against the **skills** configuration (including the **actions**, **entities**, **uris**, and **type** attributes) of the application components one by one. When all the four attributes are matched, a dialog box is displayed for users to select a matched application. ### Matching Rules of action in the want Parameter -The system matches the **action** 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 application components. + +- If **action** in the passed **want** parameter is unspecified and **actions** under **skills** of an application component is unspecified, the matching fails. -- If **action** in the passed **want** parameter is specified but **actions** under **skills** of an ability is unspecified, the matching fails. +- If **action** in the passed **want** parameter is specified but **actions** under **skills** of an application component is unspecified, the matching fails. -- If **action** in the passed **want** parameter is unspecified but **actions** under **skills** of an ability is specified, the matching is successful. +- If **action** in the passed **want** parameter is unspecified but **actions** under **skills** of an application component is specified, the matching is successful. -- If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an ability is specified and contains **action** in the passed **want** parameter, the matching is successful. +- If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an application component is specified and contains **action** in the passed **want** parameter, the matching is successful. -- If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an ability is specified but does not contain **action** in the passed **want** parameter, the matching fails. +- If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an application component 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 @@ -63,55 +69,56 @@ The system matches the **action** attribute in the **want** parameter passed by ### Matching Rules of entities in the want Parameter -The system matches the **entities** 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 application components. -- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an ability is specified, the matching is successful. +- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an application component is specified, the matching is successful. -- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an ability is unspecified, the matching is successful. +- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an application component is unspecified, the matching is successful. -- If **entities** in the passed **want** parameter is specified but **entities** under **skills** of an ability is unspecified, the matching fails. +- If **entities** in the passed **want** parameter is specified but **entities** under **skills** of an application component is unspecified, the matching fails. -- If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an ability is specified and contains **entities** in the passed **want** parameter, the matching is successful. +- If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an application component is specified and contains **entities** in the passed **want** parameter, the matching is successful. -- If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an ability is specified but does not contain **entities** in the passed **want** parameter, the matching fails. +- If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an application component 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 rules of entities in the want parameter ![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. +When the **uri** and **type** parameters are specified in the **want** parameter to initiate an application component startup request, the system traverses the list of installed components and matches the **uris** array under **skills** of the application components one by one. If one of the **uris** arrays under **skills** matches the **uri** and **type** in the passed **want**, the matching is successful. 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. - - If the **uris** array under **skills** of an ability is unspecified, the matching is successful. - - If the **uris** array under **skills** of an ability contains an URI element whose **scheme** and **type** are unspecified, the matching is successful. + - If the **uris** array under **skills** of an application component is unspecified, the matching is successful. + - If the **uris** array under **skills** of an application component contains an URI element whose **scheme** and **type** are unspecified, the matching is successful. - In other cases, the matching fails. - Only **uri** is specified in the **want** parameter. - - 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 unspecified, the matching is successful. Otherwise, the matching fails. + - If the **uris** array under **skills** of an application component is unspecified, the matching fails. + - If the **uris** array under **skills** of an application component contains an element whose [uri is matched](#matching-rules-of-uri) and **type** is unspecified, the matching is successful. Otherwise, the matching fails. - Only **type** is specified in the **want** parameter. - - 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 URI element whose **scheme** is unspecified and [type is matched](#matching-rules-of-type), the matching is successful. Otherwise, the matching fails. + - If the **uris** array under **skills** of an application component is unspecified, the matching fails. + - If the **uris** array under **skills** of an application component contains an URI element whose **scheme** is unspecified and [type is matched](#matching-rules-of-type), the matching is successful. Otherwise, the matching fails. -- Both **uri** and **type** are specified in the **want** parameter, as shown in Figure 3. - - 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. +- Both **uri** and **type** are specified in the **want** parameter, as shown below. + - If the **uris** array under **skills** of an application component is unspecified, the matching fails. + - If the **uris** array under **skills** of an application component 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**. +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 application component, 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**. **Figure 3** Matching rules when uri and type are specified in the want parameter - ![want-uri-type1](figures/want-uri-type1.png) +![want-uri-type1](figures/want-uri-type1.png) +To simplify the description: -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. +- **uri** in the **want** parameter passed in by the caller is called **w_uri**; each element in the **uris** array under **skills** of the application component to match is called **s_uri**. +- **type** in the **want** parameter passed in by the caller is called **w_type**; the type in the **uris** array under **skills** of the application component to match is called **s_type**. **Figure 4** Matching rules of uri and type in the want parameter @@ -120,7 +127,7 @@ To simplify the description, **uri** and **type** passed in the **want** paramet ### Matching Rules of uri -To simplify the description, **uri** in the passed **want** parameter is called **w_uri**; **uri** under **skills** of an ability to match is called **s_uri**. The matching rules are as follows: +The rules are as follows: - If **scheme** of **s_uri** is unspecified and **w_uri** is unspecified, the matching is successful. Otherwise, the matching fails. @@ -138,18 +145,15 @@ 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 +> The **scheme**, **host**, **port**, **path**, **pathStartWith**, and **pathRegex** attributes of **uris** under **skills** of an application component are concatenated. If **path**, **pathStartWith**, and **pathRegex** are declared in sequence, **uris** can be concatenated into the following expressions: > > - **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` +> - **Full path expression**: `scheme://host:port/path` +> - **Prefix expression**: `scheme://host:port/pathStartWith` +> - **Regular expression**: `scheme://host:port/pathRegex` ### Matching Rules of type @@ -158,7 +162,7 @@ To simplify the description, **uri** in the passed **want** parameter is called > > The matching rules of **type** described in this section are based on the fact that **type** in the **want** parameter is specified. If **type** is unspecified, follow the [matching rules of uri and type in the want parameter](#matching-rules-of-uri-and-type-in-the-want-parameter). -To simplify the description, **uri** in the passed **want** parameter is called **w_type**, and **type** of **uris** under **skills** of an ability to match is called **s_type**. The matching rules are as follows: +The matching rules are as follows: - If **s_type** is unspecified, the matching fails. diff --git a/en/application-dev/application-models/extensionability-overview.md b/en/application-dev/application-models/extensionability-overview.md index cbc50b7f1bc439b156644712531da7128409c476..719a451c6b6b468925174d5be187ae3be82e71c5 100644 --- a/en/application-dev/application-models/extensionability-overview.md +++ b/en/application-dev/application-models/extensionability-overview.md @@ -9,9 +9,9 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab - [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md): ExtensionAbility component of the form type, which provides APIs related to widgets. -- [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md): ExtensionAbility component of the work_scheduler type, which provides APIs for registering, canceling, and querying Work Scheduler tasks. +- [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md): ExtensionAbility component of the work_scheduler type, which provides callbacks for Work Scheduler tasks. -- [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which provides an input method framework that can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more. +- [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which is used to develop input method applications. - [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md): ExtensionAbility component of the service type, which provides APIs related to background service scenarios. @@ -33,6 +33,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab > > 3. Third-party applications can use other types of ExtensionAbility components that have been defined. + ## Using ExtensionAbility of the Specified Type All types of ExtensionAbility components are started by the corresponding system management service, rather than applications, so that their lifecycles are under control by the system. The caller of the ExtensionAbility component does not need to care about its lifecycle. @@ -49,20 +50,17 @@ The following uses [InputMethodExtensionAbility](../reference/apis/js-apis-input The following uses [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md) as an example. The widget framework provides the base class [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md). You derive this base class to create your own class (such as **MyFormExtensionAbility**), implement the callbacks, such as **onCreate()** and **onUpdateForm()**, to provide specific widget functionalities. For details, see [FormExtensionAbility](service-widget-overview.md). You do not need to care when to add or delete a widget. The lifecycle of the FormExtensionAbility instance and the lifecycle of the ExtensionAbility process where the FormExtensionAbility instance is located are scheduled and managed by FormManagerService. - ![form_extension](figures/form_extension.png) > **NOTE** > > For an application, all ExtensionAbility components of the same type run in an independent process, whereas UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility run in another independent process. For details, see [Process Model (Stage Model)](process-model-stage.md). -> +> > For example, an application has one UIAbility component, one ServiceExtensionAbility, one DataShareExtensionAbility, two FormExtensionAbility, and one ImeExtensionAbility. When the application is running, there are three processes: -> +> > - UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility run in an independent process. -> +> > - The two FormExtensionAbility components run in an independent process. -> +> > - The two ImeExtensionAbility components run in an independent process. - - \ No newline at end of file diff --git a/en/application-dev/application-models/fa-model-development-overview.md b/en/application-dev/application-models/fa-model-development-overview.md index f26280e2cc96cac5601b29db322affcbb323f570..db48ff10046f5277a06c80633153a0efb6124f79 100644 --- a/en/application-dev/application-models/fa-model-development-overview.md +++ b/en/application-dev/application-models/fa-model-development-overview.md @@ -3,12 +3,13 @@ During application development based on the Feature Ability (FA) model, the following tasks are involved in the application model. -**Table 1** FA model development process + + **Table 1** FA model development process | Task| Introduction| Guide| | -------- | -------- | -------- | -| Application component development| Use the PageAbility, ServiceAbility, DataAbility, and widgets of the FA model to develop applications.| - [Application- or Component-Level Configuration](application-component-configuration-fa.md)
- [PageAbility Component](pageability-overview.md)
- [ServiceAbility Component](serviceability-overview.md)
- [DataAbility Component](dataability-overview.md)
- [Widget Development](Widget-development-fa.md)
- [Context](application-context-fa.md)
- [Want](want-fa.md) | -| Inter-process communication (IPC)| Learn the process model and common IPC modes of the FA model.| [Common Events](common-event-fa.md)
[Background Services](rpc.md) | -| Inter-thread communication| Learn the thread model and common inter-thread communication modes of the FA model.| [Inter-Thread Communication](itc-fa-overview.md)| +| Application component development| Use the PageAbility, ServiceAbility, DataAbility, and widgets of the FA model to develop applications.| - [Application- or Component-Level Configuration](application-component-configuration-fa.md)
- [PageAbility Component](pageability-overview.md)
- [ServiceAbility Component](serviceability-overview.md)
- [DataAbility Component](dataability-overview.md)
- [Widget Development](widget-development-fa.md)
- [Context](application-context-fa.md)
- [Want](want-fa.md)| +| Process model| Learn the process model and common IPC modes of the FA model.| [Common Events](common-event-fa.md)
[Background Services](rpc.md)| +| Thread model| Learn the thread model and common inter-thread communication modes of the FA model.| [Inter-Thread Communication](itc-fa-overview.md)| | Mission management| Learn the basic concepts and typical scenarios of mission management in the FA model.| [Mission Management](mission-management-fa.md)| -| Application configuration file| Learn the requirements for developing application configuration files in the FA model.| [Application Configuration File](../quick-start/application-configuration-file-overview-fa.md) | +| Application configuration file| Learn the requirements for developing application configuration files in the FA model.| [Application Configuration File](../quick-start/application-configuration-file-overview-fa.md)| diff --git a/en/application-dev/application-models/figures/ability-startup-with-implicit-want1.png b/en/application-dev/application-models/figures/ability-startup-with-implicit-want1.png new file mode 100644 index 0000000000000000000000000000000000000000..3f871f4816dfcf60a5c30e39b6d0ead2f8eb711e Binary files /dev/null and b/en/application-dev/application-models/figures/ability-startup-with-implicit-want1.png differ diff --git a/en/application-dev/application-models/figures/ability-startup-with-implicit-want2.png b/en/application-dev/application-models/figures/ability-startup-with-implicit-want2.png new file mode 100644 index 0000000000000000000000000000000000000000..4f1656a3c20e472e260e8e125c42b47c11a35abb Binary files /dev/null and b/en/application-dev/application-models/figures/ability-startup-with-implicit-want2.png differ diff --git a/en/application-dev/application-models/figures/application_details.jpg b/en/application-dev/application-models/figures/application_details.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e849a47b3d10faefafbf76a7b6309da305a2e9b0 Binary files /dev/null and b/en/application-dev/application-models/figures/application_details.jpg differ diff --git a/en/application-dev/application-models/figures/stage-concepts.png b/en/application-dev/application-models/figures/stage-concepts.png index 42e99447a780b167adaf6ddd196bea4437dfa1a7..9d753f27fca4d507da20b5d5060f9b3d28e616b0 100644 Binary files a/en/application-dev/application-models/figures/stage-concepts.png and b/en/application-dev/application-models/figures/stage-concepts.png differ diff --git a/en/application-dev/application-models/figures/stage-want1.png b/en/application-dev/application-models/figures/stage-want1.png deleted file mode 100644 index 558f0a8588d7785eaad1402e68d6ba60c3118f27..0000000000000000000000000000000000000000 Binary files a/en/application-dev/application-models/figures/stage-want1.png and /dev/null differ diff --git a/en/application-dev/application-models/figures/stage-want2.png b/en/application-dev/application-models/figures/stage-want2.png deleted file mode 100644 index 72829adade52ee11419d726f19e218ec4de15220..0000000000000000000000000000000000000000 Binary files a/en/application-dev/application-models/figures/stage-want2.png and /dev/null differ diff --git a/en/application-dev/application-models/figures/start-uiability-floating-window.png b/en/application-dev/application-models/figures/start-uiability-floating-window.png new file mode 100644 index 0000000000000000000000000000000000000000..6857c9b31692419dd7937737d53424dd2b79aaed Binary files /dev/null and b/en/application-dev/application-models/figures/start-uiability-floating-window.png differ diff --git a/en/application-dev/application-models/figures/uiability-intra-device-interaction.png b/en/application-dev/application-models/figures/uiability-intra-device-interaction.png index 92292f2c6ef4c9cbd06da2a523f27b571a957e2b..344cf05e96c539ca73fdb9282625a1d1cb8584e7 100644 Binary files a/en/application-dev/application-models/figures/uiability-intra-device-interaction.png and b/en/application-dev/application-models/figures/uiability-intra-device-interaction.png differ diff --git a/en/application-dev/application-models/figures/want-action.png b/en/application-dev/application-models/figures/want-action.png index 0d8e18ce5870bea777c26b832d3f29674c2fa261..b907e8158bd9fd183ceabb181a13aa813f01e77e 100644 Binary files a/en/application-dev/application-models/figures/want-action.png and b/en/application-dev/application-models/figures/want-action.png differ diff --git a/en/application-dev/application-models/figures/widget-development-stage.png b/en/application-dev/application-models/figures/widget-development-stage.png deleted file mode 100644 index 795e96171e6d890e72a09382906302dd0fa45fab..0000000000000000000000000000000000000000 Binary files a/en/application-dev/application-models/figures/widget-development-stage.png and /dev/null 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 714698d002237cf3c2d45267596089c1317c66af..418eac519cb62c7339048df4f8663e20df8ef185 100644 --- a/en/application-dev/application-models/hop-cross-device-migration.md +++ b/en/application-dev/application-models/hop-cross-device-migration.md @@ -47,67 +47,42 @@ The table below describes the main APIs used for cross-device migration. For det ## How to Develop -1. Configure the data synchronization permission in the **module.json5** file. The sample code is as follows: - +1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). + +2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization). + +3. Configure the fields related to cross-device migration in the configuration file. + + Configure the application to support migration. + Set the **continuable** field in the **module.json5** file to **true**. The default value is **false**. If this parameter is set to **false**, the application cannot be continued on the target device. + + ```json { "module": { - "requestPermissions":[ - { - "name" : "ohos.permission.DISTRIBUTED_DATASYNC", + ... + "abilities": [ + { + ... + "continuable": true, } ] } } ``` -2. Configure the fields related to cross-device migration in the configuration file. - - Configure the application to support migration. - - - Set the **continuable** field in the **module.json5** file to **true**. The default value is **false**. If this parameter is set to **false**, the application cannot be continued on the target device. - ```json - { - "module": { - // ... - "abilities": [ - { - // ... - "continuable": true, - } - ] - } - } - ``` - - - Configure the application launch type. For details, see [UIAbility Component Launch Type](uiability-launch-type.md). - -3. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows: - - ```ts - requestPermission() { - let context = this.context - let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] - context.requestPermissionsFromUser(permissions).then((data) => { - console.info("Succeed to request permission from user with data: "+ JSON.stringify(data)) - }).catch((error) => { - console.info("Failed to request permission from user with error: "+ JSON.stringify(error)) - }) - } - ``` + Configure the application launch type. For details, see [UIAbility Component Launch Type](uiability-launch-type.md). 4. Implement [onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) in the UIAbility of the initiator. - [onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) is called on the initiator. You can save the data in this method to implement application compatibility check and migration decision. - - Saving migrated data: You can save the data to be migrated in key-value pairs in **wantParam**. - Checking application compatibility: You can obtain the version number of the target application from **wantParam** and check the compatibility between the target application and the current application. - Making a migration decision: You can determine whether to support the migration based on the return value of **onContinue()**. For details about the return value, see [Available APIs](#available-apis). - The sample code is as follows: - + The sample code is as follows: + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import AbilityConstant from '@ohos.app.ability.AbilityConstant'; diff --git a/en/application-dev/application-models/itc-with-emitter.md b/en/application-dev/application-models/itc-with-emitter.md index 2966bd8eea41e04893814f20a3c5b2f9e4e456c9..36a259d52b691459e55be502d3071135be67eb00 100644 --- a/en/application-dev/application-models/itc-with-emitter.md +++ b/en/application-dev/application-models/itc-with-emitter.md @@ -1,5 +1,6 @@ # Using Emitter for Inter-Thread Communication + [Emitter](../reference/apis/js-apis-emitter.md) provides APIs for sending and processing events between threads, including the APIs for processing events that are subscribed to in persistent or one-shot manner, unsubscribing from events, and emitting events to the event queue. @@ -13,12 +14,12 @@ To develop the Emitter mode, perform the following steps: // Define an event with eventId 1. let event = { - eventId: 1 + eventId: 1 }; // Trigger the callback after the event with eventId 1 is received. let callback = (eventData) => { - console.info('event callback'); + console.info('event callback'); }; // Subscribe to the event with eventId 1. @@ -29,21 +30,21 @@ To develop the Emitter mode, perform the following steps: ```ts import emitter from "@ohos.events.emitter"; - + // Define an event with eventId 1 and priority Low. let event = { - eventId: 1, - priority: emitter.EventPriority.LOW + eventId: 1, + priority: emitter.EventPriority.LOW }; - + let eventData = { - data: { - "content": "c", - "id": 1, - "isEmpty": false, - } + data: { + "content": "c", + "id": 1, + "isEmpty": false, + } }; - + // Emit the event with eventId 1 and event content eventData. emitter.emit(event, eventData); ``` diff --git a/en/application-dev/application-models/itc-with-worker.md b/en/application-dev/application-models/itc-with-worker.md index 996ab941b0244571dff6116a45ab5e2165cf1184..677483dbb2f4d4a6925995da680c0c18c80b8efc 100644 --- a/en/application-dev/application-models/itc-with-worker.md +++ b/en/application-dev/application-models/itc-with-worker.md @@ -1,5 +1,6 @@ # Using Worker for Inter-Thread Communication + [Worker](../reference/apis/js-apis-worker.md) is an independent thread running in parallel with the main thread. The thread that creates the worker thread is referred to as the host thread. The script file passed in during worker creation is executed in the worker thread. Generally, time-consuming operations are processed in the worker thread. However, pages cannot be directly updated in the worker thread. @@ -9,13 +10,13 @@ To develop the Worker mode, perform the following steps: 1. Configure the **buildOption** field in the [module-level build-profile.json5](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-building-configuration-0000001218440654#section6887184182020) file of the project. ```ts - "buildOption": { - "sourceOption": { - "workers": [ - "./src/main/ets/workers/worker.ts" - ] - } + "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/workers/worker.ts" + ] } + } ``` 2. Create the **worker.ts** file based on the configuration in **build-profile.json5**. @@ -27,9 +28,9 @@ To develop the Worker mode, perform the following steps: // Process messages from the main thread. parent.onmessage = function(message) { - console.info("onmessage: " + message) - // Send a message to the main thread. - parent.postMessage("message from worker thread.") + console.info("onmessage: " + message) + // Send a message to the main thread. + parent.postMessage("message from worker thread.") } ``` @@ -46,10 +47,10 @@ To develop the Worker mode, perform the following steps: // Process messages from the worker thread. wk.onmessage = function(message) { - console.info("message from worker: " + message) + console.info("message from worker: " + message) - // Stop the worker thread based on service requirements. - wk.terminate() + // Stop the worker thread based on service requirements. + wk.terminate(); } ``` @@ -57,23 +58,22 @@ To develop the Worker mode, perform the following steps: ```ts import worker from '@ohos.worker'; - + let wk = new worker.ThreadWorker("../workers/worker.ts"); - + // Send a message to the worker thread. wk.postMessage("message from main thread.") - + // Process messages from the worker thread. wk.onmessage = function(message) { - console.info("message from worker: " + message) - - // Stop the worker thread based on service requirements. - wk.terminate() + console.info("message from worker: " + message) + + // Stop the worker thread based on service requirements. + wk.terminate(); } ``` > **NOTE** -> +> > - If the relative path of **worker.ts** configured in **build-profile.json5** is **./src/main/ets/workers/worker.ts**, pass in the path **entry/ets/workers/worker.ts** when creating a worker thread in the stage model, and pass in the path **../workers/worker.ts** when creating a worker thread in the FA model. -> > - For details about the data types supported between the main thread and worker thread, see [Sequenceable Data Types](../reference/apis/js-apis-worker.md#sequenceable-data-types). diff --git a/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md b/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md index c98d39ff8348f330d58138db89afcc2a0d5995ca..51e2c75c72caa10f56cc21ad2057f9f7a94a8c12 100644 --- a/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md +++ b/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md @@ -5,7 +5,6 @@ Setting a unique icon and name for each mission snapshot of an application helps By default, the **icon** and **label** fields in the [abilities tag](../quick-start/module-configuration-file.md#abilities) of the [module.json5 file](../quick-start/module-configuration-file.md) are used to set the icon and label. Figure 1 Mission snapshot of a UIAbility - ![](figures/mission-list-recent.png) You can also use [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionicon) and [UIAbilityContext.setMissionLabel()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionlabel) to customize the icon and name for a mission snapshot. For example, for a UIAbility instance in multiton mode, you can configure the icon and name for each mission snapshot based on different functions. @@ -21,15 +20,16 @@ Call [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-inner-applica ```ts let imagePixelMap: PixelMap = undefined; // Obtain the PixelMap information. -this.context.setMissionIcon(imagePixelMap, (err) => { - console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`); +context.setMissionIcon(imagePixelMap, (err) => { + if (err.code) { + console.error(`Failed to set mission icon. Code is ${err.code}, message is ${err.message}`); + } }) ``` The display effect is shown below. Figure 2 Mission snapshot icon - ![](figures/mission-set-task-snapshot-icon.png) ## Setting a Mission Snapshot Name @@ -38,14 +38,13 @@ Call [UIAbilityContext.setMissionLabel()](../reference/apis/js-apis-inner-applic ```ts this.context.setMissionLabel('test').then(() => { - console.info('setMissionLabel succeeded.'); + console.info('Succeeded in seting mission label.'); }).catch((err) => { - console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`); + console.error(`Failed to set mission label. Code is ${err.code}, message is ${err.message}`); }); ``` The display effect is shown below. Figure 3 Mission snapshot name - ![](figures/mission-set-task-snapshot-label.png) diff --git a/en/application-dev/application-models/module-switch.md b/en/application-dev/application-models/module-switch.md index f86d416597febe296adf6bd38b6a3d87a86fdda7..8adf2dbb7608da48131c9402f4ea3b0ac09a525d 100644 --- a/en/application-dev/application-models/module-switch.md +++ b/en/application-dev/application-models/module-switch.md @@ -3,7 +3,7 @@ When switching an application from the FA model to the stage model, you must migrate the configurations under the **module** tag in the **config.json** file to the **module** tag in the **module.json5** file. -### Table 1 module Comparison +**Table 1** module comparison | Field Name in the FA Model| Field Description| Field Name in the Stage Model| Difference| | -------- | -------- | -------- | -------- | @@ -15,8 +15,8 @@ When switching an application from the FA model to the stage model, you must mig | moduleType in the distro object| Type of the HAP file. The value can be **entry** or **feature**. For the HAR type, set this field to **har**.| type | The field name is changed.| | installationFree in the distro object| Whether the HAP file supports the installation-free feature.| installationFree | The field name is changed.| | deliveryWithInstall in the distro object| Whether the HAP file is installed with the application.| deliveryWithInstall | The field name is changed.| -| metaData | Metadata of the HAP file.| metadata | See [Table 2](#table-2-metadata-comparison).| -| abilities | All abilities in the current module.| abilities | See [Table 5](#table-5-abilities-comparison).| +| metaData | Metadata of the HAP file.| metadata | For details, see Table 2.| +| abilities | All abilities in the current module.| abilities | For details, see Table 5.| | js | A set of JS modules developed using ArkUI. Each element in the set represents the information about a JS module.| pages | The stage model retains **pages** under the **module** tag. The window configuration is the lower level of **pages**.| | shortcuts | Shortcuts of the application.| shortcut_config.json| In the stage model, the **shortcut_config.json** file is defined in **resources/base/profile** in the development view.| | reqPermissions | Permissions that the application requests from the system when it is running.| requestPermissions | The field name is changed.| @@ -27,38 +27,38 @@ When switching an application from the FA model to the stage model, you must mig | entryTheme | Keyword of an OpenHarmony internal theme.| / | This configuration is not supported in the stage model.| -### Table 2 metaData Comparison +**Table 2** metaData comparison -| Field Name Under metaData in the FA Model| Field Description| Field Name Under metaData in the Stage Model| Difference| +| Field Name in the FA Model| Field Description| Field Name in the Stage Model| Difference| | -------- | -------- | -------- | -------- | | parameters | Metadata of the parameters to be passed for calling the ability.| / | This configuration is not supported in the stage model.| | results | Metadata of the ability return value.| / | This configuration is not supported in the stage model.| -| customizeData | Custom metadata of the parent component. **parameters** and **results** cannot be configured in **application**.| metadata | See [Table 3](#table-3-comparison-between-customizedata-under-metadata-in-the-fa-model-and-metadata-in-the-stage-model).| +| customizeData | Custom metadata of the parent component. **parameters** and **results** cannot be configured in **application**.| metadata | **For details**, see Table 3.| -### Table 3 Comparison Between customizeData Under metaData in the FA Model and metadata in the Stage Model +**Table 3** Comparison between customizeData under metaData in the FA model and metadata in the stage Model -| Field Name Under customizeData in metaData in the FA Model| Field Description| Field Name Under metaData in the Stage Model| Difference| +| Field Name in the FA Model| Field Description| Field Name in the Stage Model| Difference| | -------- | -------- | -------- | -------- | | name | Key name that identifies a data item. The value is a string with a maximum of 255 bytes.| name | None.| | value | Value of the data item. The value is a string with a maximum of 255 bytes.| value | None.| -| extra | Format of the current custom data. The value is the resource value of **extra**.| resource | The field name is changed. For details, see [Table 4](#table 4-metadata-examples).| +| extra | Format of the current custom data. The value is the resource value of **extra**.| resource | The field name is changed. For details, see Table 4.| -### Table 4 metaData Examples +**Table 4** metaData examples | Example in the FA Model| Example in the Stage Model| | -------- | -------- | | "meteData": {
"customizeDate": [{
"name": "label",
"value": "string",
"extra": "$string:label",
}]
} | "meteData": [{
"name": "label",
"value": "string",
"resource": "$string:label",
}] | -### Table 5 abilities Comparison +**Table 5** abilities comparison | Field Name Under abilities in the FA Model| Field Description| Field Name Under abilities in the Stage Model| Difference| | -------- | -------- | -------- | -------- | | process | Name of the process running the application or ability.| / | The stage model does not support configuration of **process** under **abilities**. The configuration of **process** is available under the **module** tag.| | uri | URI of the ability.| / | This configuration is not supported in the stage model.| | deviceCapability | Device capabilities required to run the ability.| / | This configuration is not supported in the stage model.| -| metaData | Metadata of the ability.| metadata | See [Table 2](#table-2-metadata-comparison).| +| metaData | Metadata of the ability.| metadata | For details, see Table 2.| | type | Ability type.| / | This configuration is not supported in the stage model.| | grantPermission | Whether permissions can be granted for any data in the ability.| / | The stage model does not support such a configuration under **abilities**.| | readPermission | Permission required for reading data in the ability. This field applies only to the ability using the Data template.| / | In the stage model, this configuration is available under **extensionAbilities**, but not **abilities**.| @@ -71,5 +71,5 @@ When switching an application from the FA model to the stage model, you must mig | formsEnabled | Whether the ability can provide widgets.| / | This configuration is not supported in the stage model.| | forms | Information about the widgets used by the ability. This field is valid only when **formsEnabled** is set to **true**.| form_config.json| In the stage model, the **form_config.json** file is defined in **resources/base/profile** in the development view.| | srcLanguage | Programming language used to develop the ability.| / | This configuration is not supported in the stage model.| -| srcPath | Path of the JS component code corresponding to the ability.| srcEnty | Path of the JS code corresponding to the ability.| +| srcPath | Path of the JS component code corresponding to the ability.| srcEntry | Path of the JS code corresponding to the ability.| | uriPermission | Application data that the ability can access.| / | This configuration is not supported in the stage model.| diff --git a/en/application-dev/application-models/page-mission-stack.md b/en/application-dev/application-models/page-mission-stack.md index 702cb9ba928d5266ce6720d10538df6109b0cbeb..cdb7ce724f2a29c711d4d056bcda5716f265ba48 100644 --- a/en/application-dev/application-models/page-mission-stack.md +++ b/en/application-dev/application-models/page-mission-stack.md @@ -5,7 +5,8 @@ A single UIAbility component can implement multiple pages and redirection between these pages. The redirection relationship inside the UIAbility component is called page stack, which is managed by the ArkUI framework. For example, Page1 -> Page2 -> Page3 of UIAbility1 and PageA -> PageB -> PageC of UIAbility2 in the figure below are two page stacks. - **Figure 1** Page stack +**Figure 1** Page stack + ![mission-record](figures/mission-record.png) - A page stack is formed as follows (Steps 2, 3, 5, and 6 are page redirection and managed by ArkUI): diff --git a/en/application-dev/application-models/pageability-launch-type.md b/en/application-dev/application-models/pageability-launch-type.md index 3b75ff6a60899f19f08aad5235fb3dc49632cb01..524f693c3d8c5586217d3264dedd9bde0daa16ff 100644 --- a/en/application-dev/application-models/pageability-launch-type.md +++ b/en/application-dev/application-models/pageability-launch-type.md @@ -5,7 +5,7 @@ Depending on the launch type, the action performed when the PageAbility starts d **Table 1** PageAbility launch types -| Launch Type| Meaning | Description| +| Launch Type| Meaning| Description | | -------- | -------- | -------- | | singleton | Singleton mode| Each time **startAbility()** is called, if an ability instance of this type already exists in the application process, the instance is reused. There is only one ability instance of this type in **Recents**.
A typical scenario is as follows: When a user opens a video playback application and watches a video, returns to the home screen, and opens the video playback application again, the video that the user watched before returning to the home screen is still played.| | standard | Multiton mode| Default type. Each time **startAbility()** is called, a new ability instance is created in the application process. Multiple ability instances of this type are displayed in **Recents**.
A typical scenario is as follows: When a user opens a document application and touches **New**, a new document task is created. Multiple new document missions are displayed in **Recents**.| @@ -16,13 +16,13 @@ You can set **launchType** in the **config.json** file to configure the launch t ```json { "module": { - // ... + ... "abilities": [ { // singleton means the singleton mode. // standard means the multiton mode. "launchType": "standard", - // ... + ... } ] } @@ -32,7 +32,6 @@ You can set **launchType** in the **config.json** file to configure the launch t When the PageAbility is started in multiton mode or it is started in singleton mode for the first time, the [PageAbility lifecycle callbacks](pageability-lifecycle.md#table13118194914476) are triggered. When it is not started for the first time in singleton mode, the **onNewWant()** callback (as described in the table below) is triggered, but the **onCreate()** callback is not. - **Table 2** Callbacks specific to the singleton mode | API| Description| diff --git a/en/application-dev/application-models/redirection-rules.md b/en/application-dev/application-models/redirection-rules.md index 12926c13985dbc2a535206aa4f998df2c44b2ecb..19c74c605cd7ca1451cef6809f6ec5238cec36df 100644 --- a/en/application-dev/application-models/redirection-rules.md +++ b/en/application-dev/application-models/redirection-rules.md @@ -7,14 +7,13 @@ Generally, UI redirection within an application is triggered by users. However, The PageAbility has a UI. It can use **startAbility()** to start an ability that has a UI and is visible to users. -The **exported** field under **abilities** in the **config.json** file specifies whether an ability can be started by other application components. +The **visible** field under **abilities** in the **config.json** file specifies whether an ability can be started by other application components. - -**Table 1** Description of exported +**Table 1** Description of visible | Name| Description| Initial Value Allowed| | -------- | -------- | -------- | -| exported | Whether the ability can be called by other applications.
**true**: The ability can be called by any application.
**false**: The ability can be called only by other components of the same application.| Yes (initial value: **false**)| +| visible | Whether the ability can be called by other applications.
**true**: The ability can be called by any application.
**false**: The ability can be called only by other components of the same application.| Yes (initial value: **false**)| To enable an ability to be called by any application, configure the **config.json** file as follows: @@ -22,11 +21,11 @@ To enable an ability to be called by any application, configure the **config.jso ```ts { "module": { - // ... + ... "abilities": [ { - "exported": "true", - // ... + "visible": "true", + ... } ] } @@ -34,4 +33,4 @@ To enable an ability to be called by any application, configure the **config.jso ``` -If the ability contains **skills**, you are advised to set **exported** to **true** so that the ability can be [implicitly started](explicit-implicit-want-mappings.md#matching-rules-of-implicit-want) by other applications. If this attribute is set to **false**, the system returns **PERMISSION_DENIED** when other applications attempt to start the ability. In this case, a system application can request the [START_INVISIBLE_ABILITY](../security/permission-list.md) permission to start the ability. Example abilities with **exported** set to **false** are home screen, voice assistant, or search assistant. +If the ability contains **skills**, you are advised to set **visible** to **true** so that the ability can be [implicitly started](explicit-implicit-want-mappings.md) by other applications. If this attribute is set to **false**, the system returns **PERMISSION_DENIED** when other applications attempt to start the ability. In this case, a system application can request the [START_INVISIBLE_ABILITY](../security/permission-list.md) permission to start the ability. Example abilities with **visible** set to **false** are home screen, voice assistant, or search assistant. diff --git a/en/application-dev/application-models/request-permissions.md b/en/application-dev/application-models/request-permissions.md index 670860d87dbb56adceb02f4ca350c24b61260d30..a29b793c9949d1080c8322681ba27cf6495f29ac 100644 --- a/en/application-dev/application-models/request-permissions.md +++ b/en/application-dev/application-models/request-permissions.md @@ -9,37 +9,7 @@ During application development, you must declare the required permission in the To declare a permission in **config.json**, add **reqPermissions** under **module** and list the permission. +For example, to request the permission to access the calendar, perform the following steps: -For example, to declare the permission to access the calendar, request the **ohos.permission.READ_CALENDAR** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). - - -The sample code in the **config.json** file is as follows: - -```json -{ - "module": { - // ... - "reqPermissions": [ - { - "name": "ohos.permission.READ_CALENDAR" - // ... - } - ] - } -} -``` - - -Request the permission from uses in the form of a dialog box: - -```ts -import featureAbility from '@ohos.ability.featureAbility'; - -let context = featureAbility.getContext(); -let permissions: Array = ['ohos.permission.READ_CALENDAR'] -context.requestPermissionsFromUser(permissions, 1).then((data) => { - console.info("Succeed to request permission from user with data: " + JSON.stringify(data)) -}).catch((error) => { - console.info("Failed to request permission from user with error: " + JSON.stringify(error)) -}) -``` +1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). +2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization). diff --git a/en/application-dev/application-models/serviceextensionability.md b/en/application-dev/application-models/serviceextensionability.md index 2e9aaeb48100d86d0cd1c7a0e69ea01bf4ef2340..555a288f4726a2bfbb9db9cf0c26b1cb8e799b04 100644 --- a/en/application-dev/application-models/serviceextensionability.md +++ b/en/application-dev/application-models/serviceextensionability.md @@ -29,6 +29,7 @@ Note the following: [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) provides the callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestory()**. Override them as required. The following figure shows the lifecycle of ServiceExtensionAbility. **Figure 1** ServiceExtensionAbility lifecycle + ![ServiceExtensionAbility-lifecycle](figures/ServiceExtensionAbility-lifecycle.png) - **onCreate** @@ -109,7 +110,7 @@ export default class ServiceExtImpl extends IdlServiceExtStub { insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void { // Implement service logic. - console.log(TAG, `insertDataToMap, key: ${key} val: ${val}`); + console.info(TAG, `insertDataToMap, key: ${key} val: ${val}`); callback(ERR_OK); } } @@ -175,7 +176,7 @@ To manually create a ServiceExtensionAbility in the DevEco Studio project, perfo ```json { "module": { - // ... + ... "extensionAbilities": [ { "name": "ServiceExtAbility", @@ -201,41 +202,43 @@ A system application uses the [startServiceExtensionAbility()](../reference/apis 1. Start a new ServiceExtensionAbility in a system application. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). ```ts + let context = ...; // UIAbilityContext let want = { - "deviceId": "", - "bundleName": "com.example.myapplication", - "abilityName": "ServiceExtAbility" + "deviceId": "", + "bundleName": "com.example.myapplication", + "abilityName": "ServiceExtAbility" }; - this.context.startServiceExtensionAbility(want).then(() => { - console.info('startServiceExtensionAbility success'); - }).catch((error) => { - console.info('startServiceExtensionAbility failed'); + context.startServiceExtensionAbility(want).then(() => { + console.info('Succeeded in starting ServiceExtensionAbility.'); + }).catch((err) => { + console.error(`Failed to start ServiceExtensionAbility. Code is ${err.code}, message is ${err.message}`); }) ``` 2. Stop ServiceExtensionAbility in the system application. ```ts + let context = ...; // UIAbilityContext let want = { - "deviceId": "", - "bundleName": "com.example.myapplication", - "abilityName": "ServiceExtAbility" + "deviceId": "", + "bundleName": "com.example.myapplication", + "abilityName": "ServiceExtAbility" }; - this.context.stopServiceExtensionAbility(want).then(() => { - console.info('stopServiceExtensionAbility success'); - }).catch((error) => { - console.info('stopServiceExtensionAbility failed'); + context.stopServiceExtensionAbility(want).then(() => { + console.info('Succeeded in stoping ServiceExtensionAbility.'); + }).catch((err) => { + console.error(`Failed to stop ServiceExtensionAbility. Code is ${err.code}, message is ${err.message}`); }) ``` 3. ServiceExtensionAbility stops itself. ```ts - // this is the current ServiceExtensionAbility component. - this.context.terminateSelf().then(() => { - console.info('terminateSelf success'); - }).catch((error) => { - console.info('terminateSelf failed'); + let context = ...; // ServiceExtensionContext + context.terminateSelf().then(() => { + console.info('Succeeded in terminating self.'); + }).catch((err) => { + console.error(`Failed to terminate self. Code is ${err.code}, message is ${err.message}`); }) ``` @@ -257,27 +260,27 @@ The ServiceExtensionAbility component returns an IRemoteObject in the **onConnec ```ts let want = { - "deviceId": "", - "bundleName": "com.example.myapplication", - "abilityName": "ServiceExtAbility" + "deviceId": "", + "bundleName": "com.example.myapplication", + "abilityName": "ServiceExtAbility" }; let options = { - onConnect(elementName, remote) { - /* The input parameter remote is the object returned by ServiceExtensionAbility in the onConnect lifecycle callback. - * This object is used for communication with ServiceExtensionAbility. For details, see the section below. - */ - console.info('onConnect callback'); - if (remote === null) { - console.info(`onConnect remote is null`); - return; - } - }, - onDisconnect(elementName) { - console.info('onDisconnect callback') - }, - onFailed(code) { - console.info('onFailed callback') + onConnect(elementName, remote) { + /* The input parameter remote is the object returned by ServiceExtensionAbility in the onConnect lifecycle callback. + * This object is used for communication with ServiceExtensionAbility. For details, see the section below. + */ + console.info('onConnect callback'); + if (remote === null) { + console.info(`onConnect remote is null`); + return; } + }, + onDisconnect(elementName) { + console.info('onDisconnect callback') + }, + onFailed(code) { + console.info('onFailed callback') + } } // The ID returned after the connection is set up must be saved. The ID will be passed for service disconnection. let connectionId = this.context.connectServiceExtensionAbility(want, options); @@ -288,9 +291,9 @@ The ServiceExtensionAbility component returns an IRemoteObject in the **onConnec ```ts // connectionId is returned when connectServiceExtensionAbility is called and needs to be manually maintained. this.context.disconnectServiceExtensionAbility(connectionId).then((data) => { - console.info('disconnectServiceExtensionAbility success'); + console.info('disconnectServiceExtensionAbility success'); }).catch((error) => { - console.error('disconnectServiceExtensionAbility failed'); + console.error('disconnectServiceExtensionAbility failed'); }) ``` @@ -305,27 +308,27 @@ After obtaining the [rpc.RemoteObject](../reference/apis/js-apis-rpc.md#iremoteo import IdlServiceExtProxy from '../IdlServiceExt/idl_service_ext_proxy'; let options = { - onConnect(elementName, remote) { - console.info('onConnect callback'); - if (remote === null) { - console.info(`onConnect remote is null`); - return; - } - let serviceExtProxy = new IdlServiceExtProxy(remote); - // Communication is carried out by interface calling, without exposing RPC details. - serviceExtProxy.processData(1, (errorCode, retVal) => { - console.log(`processData, errorCode: ${errorCode}, retVal: ${retVal}`); - }); - serviceExtProxy.insertDataToMap('theKey', 1, (errorCode) => { - console.log(`insertDataToMap, errorCode: ${errorCode}`); - }) - }, - onDisconnect(elementName) { - console.info('onDisconnect callback') - }, - onFailed(code) { - console.info('onFailed callback') + onConnect(elementName, remote) { + console.info('onConnect callback'); + if (remote === null) { + console.info(`onConnect remote is null`); + return; } + let serviceExtProxy = new IdlServiceExtProxy(remote); + // Communication is carried out by interface calling, without exposing RPC details. + serviceExtProxy.processData(1, (errorCode, retVal) => { + console.info(`processData, errorCode: ${errorCode}, retVal: ${retVal}`); + }); + serviceExtProxy.insertDataToMap('theKey', 1, (errorCode) => { + console.info(`insertDataToMap, errorCode: ${errorCode}`); + }) + }, + onDisconnect(elementName) { + console.info('onDisconnect callback') + }, + onFailed(code) { + console.info('onFailed callback') + } } ``` @@ -333,40 +336,40 @@ After obtaining the [rpc.RemoteObject](../reference/apis/js-apis-rpc.md#iremoteo ```ts import rpc from '@ohos.rpc'; - + const REQUEST_CODE = 1; let options = { - onConnect(elementName, remote) { - console.info('onConnect callback'); - if (remote === null) { - console.info(`onConnect remote is null`); - return; - } - // Directly call the RPC interface to send messages to the server. The client needs to serialize the input parameters and deserialize the return values. The process is complex. - let option = new rpc.MessageOption(); - let data = new rpc.MessageSequence(); - let reply = new rpc.MessageSequence(); - data.writeInt(100); - - // @param code Indicates the service request code sent by the client. - // @param data Indicates the {@link MessageSequence} object sent by the client. - // @param reply Indicates the response message object sent by the remote service. - // @param options Specifies whether the operation is synchronous or asynchronous. - // - // @return Returns {@code true} if the operation is successful; returns {@code false} otherwise. - remote.sendMessageRequest(REQUEST_CODE, data, reply, option).then((ret) => { - let msg = reply.readInt(); - console.info(`sendMessageRequest ret:${ret} msg:${msg}`); - }).catch((error) => { - console.info('sendMessageRequest failed'); - }); - }, - onDisconnect(elementName) { - console.info('onDisconnect callback') - }, - onFailed(code) { - console.info('onFailed callback') + onConnect(elementName, remote) { + console.info('onConnect callback'); + if (remote === null) { + console.info(`onConnect remote is null`); + return; } + // Directly call the RPC interface to send messages to the server. The client needs to serialize the input parameters and deserialize the return values. The process is complex. + let option = new rpc.MessageOption(); + let data = new rpc.MessageSequence(); + let reply = new rpc.MessageSequence(); + data.writeInt(100); + + // @param code Indicates the service request code sent by the client. + // @param data Indicates the {@link MessageSequence} object sent by the client. + // @param reply Indicates the response message object sent by the remote service. + // @param options Specifies whether the operation is synchronous or asynchronous. + // + // @return Returns {@code true} if the operation is successful; returns {@code false} otherwise. + remote.sendMessageRequest(REQUEST_CODE, data, reply, option).then((ret) => { + let msg = reply.readInt(); + console.info(`sendMessageRequest ret:${ret} msg:${msg}`); + }).catch((error) => { + console.info('sendMessageRequest failed'); + }); + }, + onDisconnect(elementName) { + console.info('onDisconnect callback') + }, + onFailed(code) { + console.info('onFailed callback') + } } ``` @@ -381,8 +384,8 @@ When ServiceExtensionAbility is used to provide sensitive services, the client i ```ts import rpc from '@ohos.rpc'; import bundleManager from '@ohos.bundle.bundleManager'; - import {processDataCallback} from './i_idl_service_ext'; - import {insertDataToMapCallback} from './i_idl_service_ext'; + import { processDataCallback } from './i_idl_service_ext'; + import { insertDataToMapCallback } from './i_idl_service_ext'; import IdlServiceExtStub from './idl_service_ext_stub'; const ERR_OK = 0; @@ -397,7 +400,7 @@ When ServiceExtensionAbility is used to provide sensitive services, the client i bundleManager.getBundleNameByUid(callerUid).then((callerBundleName) => { console.info(TAG, 'getBundleNameByUid: ' + callerBundleName); // Identify the bundle name of the client. - if (callerBundleName != 'com.example.connectextapp') { // The verification fails. + if (callerBundleName != 'com.example.connectextapp') { // The verification fails. console.info(TAG, 'The caller bundle is not in whitelist, reject'); return; } @@ -409,7 +412,7 @@ When ServiceExtensionAbility is used to provide sensitive services, the client i insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void { // Implement service logic. - console.log(TAG, `insertDataToMap, key: ${key} val: ${val}`); + console.info(TAG, `insertDataToMap, key: ${key} val: ${val}`); callback(ERR_OK); } } @@ -425,15 +428,15 @@ When ServiceExtensionAbility is used to provide sensitive services, the client i import {processDataCallback} from './i_idl_service_ext'; import {insertDataToMapCallback} from './i_idl_service_ext'; import IdlServiceExtStub from './idl_service_ext_stub'; - + const ERR_OK = 0; const ERR_DENY = -1; const TAG: string = "[IdlServiceExtImpl]"; - + export default class ServiceExtImpl extends IdlServiceExtStub { processData(data: number, callback: processDataCallback): void { console.info(TAG, `processData: ${data}`); - + let callerTokenId = rpc.IPCSkeleton.getCallingTokenId(); let accessManger = abilityAccessCtrl.createAtManager(); // The permission to be verified varies depending on the service requirements. ohos.permission.SET_WALLPAPER is only an example. @@ -446,10 +449,10 @@ When ServiceExtensionAbility is used to provide sensitive services, the client i } callback(ERR_OK, data + 1); // The verification is successful, and service logic is executed normally. } - + insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void { // Implement service logic. - console.log(TAG, `insertDataToMap, key: ${key} val: ${val}`); + console.info(TAG, `insertDataToMap, key: ${key} val: ${val}`); callback(ERR_OK); } } diff --git a/en/application-dev/application-models/stage-model-development-overview.md b/en/application-dev/application-models/stage-model-development-overview.md index cfd6cd6a96b79b03541e01b3af4fa5667c315289..d4ad1d87c602c169e13b9ff99b8b491a33babd0a 100644 --- a/en/application-dev/application-models/stage-model-development-overview.md +++ b/en/application-dev/application-models/stage-model-development-overview.md @@ -12,7 +12,7 @@ The following figure shows the basic concepts used in the stage model. The stage model provides two types of application components: UIAbility and ExtensionAbility. Both have specific classes and support object-oriented development. - - UIAbility has the UI and is mainly used for user interaction. For example, with UIAbility, the Gallery application can display images in the liquid layout. After a user selects an image, it uses a new UI to display the image details. The user can touch the **Back** button to return to the liquid layout. The lifecycle of the UIAbility component contains the creation, destruction, foreground, and background states. Display-related states are exposed through WindowStage events. + - UIAbility is a type of application component that provides the UI for user interaction. For example, with UIAbility, the Gallery application can display images in the liquid layout. After a user selects an image, it uses a new UI to display the image details. The user can touch the **Back** button to return to the liquid layout. The lifecycle of the UIAbility component contains the creation, destruction, foreground, and background states. Display-related states are exposed through WindowStage events. - ExtensionAbility is oriented to specific scenarios. You cannot derive directly from ExtensionAbility. Instead, use the derived classes of ExtensionAbility for your scenarios, such as FormExtensionAbility for widget scenarios, InputMethodExtensionAbility for input method scenarios, and WorkSchedulerExtensionAbility for Work Scheduled task scenarios. For example, to enable a user to create an application widget on the home screen, you must derive FormExtensionAbility, implement the callback functions, and configure the capability in the configuration file. The derived class instances are created by developers and their lifecycles are managed by the system. In the stage model, you must use the derived classes of ExtensionAbility to develop custom services based on your service scenarios. - [WindowStage](../windowmanager/application-window-stage.md) @@ -21,7 +21,7 @@ The following figure shows the basic concepts used in the stage model. - [Context](application-context-stage.md) - In the stage model, Context and its derived classes provide a variety of capabilities that can be called during the runtime. The UIAbility component and ExtensionAbility derived classes have different Context classes. These classes, which all inherit from the base class Context, provide different capabilities. + In the stage model, Context and its derived classes provide a variety of resources and capabilities that can be called during the runtime. The UIAbility component and ExtensionAbility derived classes have different Context classes. These classes, which all inherit from the base class Context, provide different capabilities. - [AbilityStage](abilitystage.md) @@ -37,7 +37,7 @@ During application development based on the stage model, the following tasks are | Task| Introduction| Guide| | -------- | -------- | -------- | | Application component development| Use the UIAbility and ExtensionAbility components of the stage model to develop applications.| - [Application- or Component-Level Configuration](application-component-configuration-stage.md)
- [UIAbility Component](uiability-overview.md)
- [ExtensionAbility Component](extensionability-overview.md)
- [AbilityStage Container Component](abilitystage.md)
- [Context](application-context-stage.md)
- [Component Startup Rules](component-startup-rules.md)| -| Inter-process communication (IPC)| Learn the process model and common IPC modes of the stage model.| - [Common Events](common-event-overview.md)
- [Background Services](background-services.md)| -| Inter-thread communication| Learn the thread model and common inter-thread communication modes of the stage model.| - [Emitter](itc-with-emitter.md)
- [Worker](itc-with-worker.md)| +| Process model| Learn the process model and common IPC modes of the stage model.| - [Common Events](common-event-overview.md)
- [Background Services](background-services.md)| +| Thread model| Learn the thread model and common inter-thread communication modes of the stage model.| - [Emitter](itc-with-emitter.md)
- [Worker](itc-with-worker.md)| | Mission management| Learn the basic concepts and typical scenarios of mission management in the stage model.| - [Mission Management Scenarios](mission-management-overview.md)
- [Mission Management and Launch Type](mission-management-launch-type.md)
- [Page Stack and Mission List](page-mission-stack.md)| -| Application configuration file| Learn the requirements for developing application configuration files in the stage model.| [Application Configuration File](../quick-start/application-configuration-file-overview-stage.md)| +| Application configuration file| Learn the requirements for developing application configuration files in the stage model.| [Application Configuration File](config-file-stage.md)| diff --git a/en/application-dev/application-models/start-page.md b/en/application-dev/application-models/start-page.md index 4296d832fdaafaba67544e8e62b5c7c08395ecdf..1def472cd5fa2567fda123fc272542787b1f985c 100644 --- a/en/application-dev/application-models/start-page.md +++ b/en/application-dev/application-models/start-page.md @@ -12,7 +12,7 @@ import featureAbility from '@ohos.ability.featureAbility'; async function restartAbility() { let wantInfo = { bundleName: "com.sample.MyApplication", - abilityName: "MainAbility", + abilityName: "EntryAbility", parameters: { page: "pages/second" } @@ -83,13 +83,13 @@ struct Index { @State message: string = 'Hello World' build() { - // ... + ... Button("startAbility") .onClick(() => { featureAbility.startAbility({ want: { bundleName: "com.exm.myapplication", - abilityName: "com.exm.myapplication.MainAbility", + abilityName: "com.exm.myapplication.EntryAbility", parameters: { page: "pages/page1" } } }).then((data) => { @@ -98,13 +98,13 @@ struct Index { console.info("startAbility failed errcode:" + err.code) }) }) - // ... + ... Button("page2") .onClick(() => { featureAbility.startAbility({ want: { bundleName: "com.exm.myapplication", - abilityName: "com.exm.myapplication.MainAbility", + abilityName: "com.exm.myapplication.EntryAbility", parameters: { page: "pages/page2" } } }).then((data) => { @@ -113,7 +113,7 @@ struct Index { console.info("startAbility failed errcode:" + err.code) }) }) - // ... + ... } } ``` @@ -136,7 +136,7 @@ export default { }) }, onDestroy() { - // ... + ... }, } ``` diff --git a/en/application-dev/application-models/start-pageability-from-stage.md b/en/application-dev/application-models/start-pageability-from-stage.md index 9d1b7ed27f6780ce56d1e90b3be5d196cf3b1187..bd6a11187fdfbc81c63bcc6601f8a8e82b0dbe4c 100644 --- a/en/application-dev/application-models/start-pageability-from-stage.md +++ b/en/application-dev/application-models/start-pageability-from-stage.md @@ -21,7 +21,7 @@ export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { console.info("EntryAbility onWindowStageCreate") windowStage.loadContent('pages/Index', (err, data) => { - // ... + ... }); let want = { bundleName: "com.ohos.fa", @@ -66,7 +66,7 @@ export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { console.info("EntryAbility onWindowStageCreate") windowStage.loadContent('pages/Index', (err, data) => { - // ... + ... }); let want = { bundleName: "com.ohos.fa", diff --git a/en/application-dev/application-models/start-remote-pageability.md b/en/application-dev/application-models/start-remote-pageability.md index 36ee305b49698c1f6e6cf216174f77212f1d53e4..a52378af306c9719b086b23f0909f87d7bf376b3 100644 --- a/en/application-dev/application-models/start-remote-pageability.md +++ b/en/application-dev/application-models/start-remote-pageability.md @@ -83,28 +83,31 @@ After obtaining the data synchronization permission, obtain the trusted device l The following sample code shows how to use **getTrustedDeviceListSync()** to obtain the trusted device list. ```ts -import deviceManager from '@ohos.distributedHardware.deviceManager'; -let dmClass; +import deviceManager from '@ohos.distributedHardware.deviceManager'; + +let dmClass; + function getDeviceManager() { - deviceManager.createDeviceManager('ohos.example.distributedService', (error, dm) => { - if (error) { - console.info('create device manager failed with ' + error) - } - dmClass = dm; - }) + deviceManager.createDeviceManager('ohos.example.distributedService', (error, dm) => { + if (error) { + console.info('create device manager failed with ' + error) + } + dmClass = dm; + }) } -function getRemoteDeviceId() { - if (typeof dmClass === 'object' && dmClass != null) { - let list = dmClass.getTrustedDeviceListSync(); - if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.info("EntryAbility onButtonClick getRemoteDeviceId err: list is null"); - return; - } - console.info("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); - return list[0].deviceId; - } else { - console.info("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null"); - } + +function getRemoteDeviceId() { + if (typeof dmClass === 'object' && dmClass != null) { + let list = dmClass.getTrustedDeviceListSync(); + if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { + console.info("EntryAbility onButtonClick getRemoteDeviceId err: list is null"); + return; + } + console.info("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); + return list[0].deviceId; + } else { + console.info("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null"); + } } ``` @@ -116,21 +119,22 @@ The following sample code shows how to explicitly start a remote PageAbility thr ```ts import featureAbility from '@ohos.ability.featureAbility'; -function onStartRemoteAbility() { - console.info('onStartRemoteAbility begin'); - let params; - let wantValue = { - bundleName: 'ohos.samples.etsDemo', - abilityName: 'ohos.samples.etsDemo.RemoteAbility', - deviceId: getRemoteDeviceId(), // getRemoteDeviceId is defined in the preceding sample code. - parameters: params - }; - console.info('onStartRemoteAbility want=' + JSON.stringify(wantValue)); - featureAbility.startAbility({ - want: wantValue - }).then((data) => { - console.info('onStartRemoteAbility finished, ' + JSON.stringify(data)); - }); - console.info('onStartRemoteAbility end'); + +function onStartRemoteAbility() { + console.info('onStartRemoteAbility begin'); + let params; + let wantValue = { + bundleName: 'ohos.samples.etsDemo', + abilityName: 'ohos.samples.etsDemo.RemoteAbility', + deviceId: getRemoteDeviceId(), // getRemoteDeviceId is defined in the preceding sample code. + parameters: params + }; + console.info('onStartRemoteAbility want=' + JSON.stringify(wantValue)); + featureAbility.startAbility({ + want: wantValue + }).then((data) => { + console.info('onStartRemoteAbility finished, ' + JSON.stringify(data)); + }); + console.info('onStartRemoteAbility end'); } ``` diff --git a/en/application-dev/application-models/start-serviceability.md b/en/application-dev/application-models/start-serviceability.md index f3b0f6aeabc8a3ea35c1f6c390ec53239730443c..e07428f13a5ce3a3981b7881387dc8498f1380d1 100644 --- a/en/application-dev/application-models/start-serviceability.md +++ b/en/application-dev/application-models/start-serviceability.md @@ -27,7 +27,7 @@ async function startServiceAbility() { ``` -In the preceding code, **startAbility()** is used to start the ServiceAbility. +In the preceding code, [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is used to start the ServiceAbility. - If the ServiceAbility is not running, the system calls **onStart()** to initialize the ServiceAbility, and then calls **onCommand()** on the ServiceAbility. diff --git a/en/application-dev/application-models/subscribe-system-environment-variable-changes.md b/en/application-dev/application-models/subscribe-system-environment-variable-changes.md index c231f483e9bcd8f83faf49d40007730d0f854de5..4eecf15808da492ca69d933fdabf39aa82347ce5 100644 --- a/en/application-dev/application-models/subscribe-system-environment-variable-changes.md +++ b/en/application-dev/application-models/subscribe-system-environment-variable-changes.md @@ -54,7 +54,7 @@ In OpenHarmony, you can subscribe to system environment variable changes in the // Page display. build() { - // ... + ... } } ``` @@ -77,7 +77,7 @@ In OpenHarmony, you can subscribe to system environment variable changes in the // Page display. build() { - // ... + ... } } ``` @@ -99,19 +99,19 @@ import AbilityStage from '@ohos.app.ability.AbilityStage'; let systemLanguage: string; // System language in use. export default class MyAbilityStage extends AbilityStage { - onCreate() { - systemLanguage = this.context.config.language; // Obtain the system language in use when the AbilityStage instance is loaded for the first time. - console.info(`systemLanguage is ${systemLanguage} `); - } + onCreate() { + systemLanguage = this.context.config.language; // Obtain the system language in use when the AbilityStage instance is loaded for the first time. + console.info(`systemLanguage is ${systemLanguage} `); + } - onConfigurationUpdate(newConfig) { - console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); + onConfigurationUpdate(newConfig) { + console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); - if (systemLanguage !== newConfig.language) { - console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); - systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. - } + if (systemLanguage !== newConfig.language) { + console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); + systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. } + } } ``` @@ -131,21 +131,21 @@ import UIAbility from '@ohos.app.ability.UIAbility'; let systemLanguage: string; // System language in use. export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - systemLanguage = this.context.config.language; // Obtain the system language in use when the UIAbility instance is loaded for the first time. - console.info(`systemLanguage is ${systemLanguage} `); - } + onCreate(want, launchParam) { + systemLanguage = this.context.config.language; // Obtain the system language in use when the UIAbility instance is loaded for the first time. + console.info(`systemLanguage is ${systemLanguage} `); + } - onConfigurationUpdate(newConfig) { - console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); + onConfigurationUpdate(newConfig) { + console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); - if (systemLanguage !== newConfig.language) { - console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); - systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. - } + if (systemLanguage !== newConfig.language) { + console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); + systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. } + } - // ... + ... } ``` @@ -163,10 +163,10 @@ The code snippet below uses FormExtensionAbility as an example to describe how t import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; export default class EntryFormAbility extends FormExtensionAbility { - onConfigurationUpdate(newConfig) { - console.info(`newConfig is ${JSON.stringify(newConfig)}`); - } + onConfigurationUpdate(newConfig) { + console.info(`newConfig is ${JSON.stringify(newConfig)}`); + } - // ... + ... } ``` diff --git a/en/application-dev/application-models/thread-model-fa.md b/en/application-dev/application-models/thread-model-fa.md index 0f11cddb48792e887a14a2d5011dbdcd4736340d..f6b335f8932ee1ebd5bb9bdf11db99ff354a1470 100644 --- a/en/application-dev/application-models/thread-model-fa.md +++ b/en/application-dev/application-models/thread-model-fa.md @@ -1,13 +1,11 @@ # Thread Model Overview (FA Model) - There are three types of threads in the FA model: - - Main thread - + Manages other threads. - + - Ability thread - One ability thread for each ability. - Distributes input events. @@ -16,13 +14,11 @@ There are three types of threads in the FA model: - Receives messages sent by the worker thread. - Worker thread - + Performs time-consuming operations - Based on the OpenHarmony thread model, different services run on different threads. Service interaction requires inter-thread communication. Threads can communicate with each other in Emitter or Worker mode. Emitter is mainly used for event synchronization between threads, and Worker is mainly used to execute time-consuming tasks. - > **NOTE** > > The FA model provides an independent thread for each ability. Emitter is mainly used for event synchronization within the ability thread, between a pair of ability threads, or between the ability thread and worker thread. diff --git a/en/application-dev/application-models/thread-model-stage.md b/en/application-dev/application-models/thread-model-stage.md index 7343b9b619a5d68354e65e254a22a2b078ca44ee..2b1f855980a14eeba89a18184c69d46eebaea6ac 100644 --- a/en/application-dev/application-models/thread-model-stage.md +++ b/en/application-dev/application-models/thread-model-stage.md @@ -17,5 +17,6 @@ Based on the OpenHarmony thread model, different services run on different threa > **NOTE** > -> - The stage model provides only the main thread and worker thread. Emitter is mainly used for event synchronization within the main thread or between the main thread and worker thread. -> - To view thread information about an application process, run the **hdc shell** command to enter the shell CLI of the device, and then run the **ps -p ** -T command**, where ** indicates the ID of the application process. +> - The stage model provides only the main thread and worker thread. Emitter is mainly used for event synchronization within the worker thread or between the main thread and worker thread. +> - The UIAbility and UI are in the main thread. For details about data synchronization between them, see [Data Synchronization Between UIAbility and UI](uiability-data-sync-with-ui.md). +> - To view thread information about an application process, run the **hdc shell** command to enter the shell CLI of the device, and then run the **ps -p ** -T command**, where ** indicates the [process ID](process-model-stage.md) of the application. diff --git a/en/application-dev/application-models/uiability-data-sync-with-ui.md b/en/application-dev/application-models/uiability-data-sync-with-ui.md index f53627e974a0f9b4b1323d7694f94e07ebf51753..6998001c763a464e51f8cef4a0c64aec6f1db5e8 100644 --- a/en/application-dev/application-models/uiability-data-sync-with-ui.md +++ b/en/application-dev/application-models/uiability-data-sync-with-ui.md @@ -3,17 +3,16 @@ Based on the OpenHarmony application model, you can use any of the following ways to implement data synchronization between the UIAbility component and UI: -- EventHub: The [base class Context](application-context-stage.md) provides the EventHub capability. It is implemented based on the publish/subscribe (pub/sub) pattern. Your application subscribes to an event and when the event occurs, receives a notification. - -- globalThis: It is a global object accessible in the ArkTS engine instance. -- LocalStorage/AppStorage: See [State Management of Application-Level Variables](../quick-start/arkts-state-mgmt-application-level.md). +- [Using EventHub for Data Synchronization](#using-eventhub-for-data-synchronization): The **EventHub** object is provided by the base class **Context**. Events are transferred using the publish/subscribe (pub/sub) pattern. Specifically, after subscribing to an event, your application will receive the event and process it accordingly when the event is published. +- [Using globalThis for Data Synchronization](#using-globalthis-for-data-synchronization): **globalThis** is a global object inside the ArkTS engine instance and can be accessed by components such as UIAbility, ExtensionAbility, and Page. +- [Using AppStorage or LocalStorage for Data Synchronization](#using-appstorage-or-localstorage-for-data-synchronization): ArkUI provides two application-level state management solutions: AppStorage and LocalStorage, which implement application- and UIAbility-level data synchronization, respectively. ## Using EventHub for Data Synchronization -[EventHub](../reference/apis/js-apis-inner-application-eventHub.md) provides an event mechanism at the UIAbility or ExtensionAbility component level. Centered on the UIAbility or ExtensionAbility component, EventHub provides data communication capabilities for subscribing to, unsubscribing from, and triggering events. +[EventHub](../reference/apis/js-apis-inner-application-eventHub.md) provides an event mechanism for the UIAbility or ExtensionAbility component so that they can subscribe to, unsubscribe from, and trigger events. -Before using EventHub, you must obtain an EventHub object, which is provided by the [base class Context](application-context-stage.md). This section uses EventHub as an example to describe how to implement data synchronization between the UIAbility component and the UI. +Before using the APIs provided by **EventHub**, you must obtain an **EventHub** object, which is provided by the [base class Context](application-context-stage.md). This section uses EventHub as an example to describe how to implement data synchronization between the UIAbility component and the UI. 1. Call [eventHub.on()](../reference/apis/js-apis-inner-application-eventHub.md#eventhubon) in the UIAbility in either of the following ways to register a custom event **event1**. @@ -23,21 +22,21 @@ Before using EventHub, you must obtain an EventHub object, which is provided by const TAG: string = '[Example].[Entry].[EntryAbility]'; export default class EntryAbility extends UIAbility { - func1(...data) { - // Trigger the event to complete the service operation. - console.info(TAG, '1. ' + JSON.stringify(data)); - } - - onCreate(want, launch) { - // Obtain an eventHub object. - let eventhub = this.context.eventHub; - // Subscribe to the event. - eventhub.on('event1', this.func1); - eventhub.on('event1', (...data) => { - // Trigger the event to complete the service operation. - console.info(TAG, '2. ' + JSON.stringify(data)); - }); - } + func1(...data) { + // Trigger the event to complete the service operation. + console.info(TAG, '1. ' + JSON.stringify(data)); + } + + onCreate(want, launch) { + // Obtain an eventHub object. + let eventhub = this.context.eventHub; + // Subscribe to the event. + eventhub.on('event1', this.func1); + eventhub.on('event1', (...data) => { + // Trigger the event to complete the service operation. + console.info(TAG, '2. ' + JSON.stringify(data)); + }); + } } ``` @@ -63,7 +62,7 @@ Before using EventHub, you must obtain an EventHub object, which is provided by // Page display. build() { - // ... + ... } } ``` @@ -81,44 +80,42 @@ Before using EventHub, you must obtain an EventHub object, which is provided by 4. After **event1** is used, you can call [eventHub.off()](../reference/apis/js-apis-inner-application-eventHub.md#eventhuboff) to unsubscribe from the event. ```ts - // context is the ability context of the UIAbility instance. + // context is the AbilityContext of the UIAbility instance. this.context.eventHub.off('event1'); ``` ## Using globalThis for Data Synchronization - **globalThis** is a global object inside the [ArkTS engine instance](thread-model-stage.md) and can be used by UIAbility, ExtensionAbility, and Page inside the engine. Therefore, you can use **globalThis** for data synchronization. - **Figure 1** Using globalThis for data synchronization - - ![globalThis1](figures/globalThis1.png) +**Figure 1** Using globalThis for data synchronization +![globalThis1](figures/globalThis1.png) The following describes how to use **globalThis** in three scenarios. Precautions are provided as well. - [Using globalThis Between UIAbility and Page](#using-globalthis-between-uiability-and-page) -- [Using globalThis Between UIAbility and UIAbility](##using-globalthis-between-uiability-and-uiability) +- [Using globalThis Between UIAbility and UIAbility](#using-globalthis-between-uiability-and-uiability) - [Use globalThis Between UIAbility and ExtensionAbility](#using-globalthis-between-uiability-and-extensionability) - [Precautions for Using globalThis](#precautions-for-using-globalthis) ### Using globalThis Between UIAbility and Page -You can use **globalThis** to bind attributes or methods to implement data synchronization between the UIAbility component and UI. For example, if you bind the **want** parameter in the UIAbility component, you can use the **want** parameter information on the UI corresponding to the UIAbility component. +By binding attributes or methods to **globalThis**, you can implement data synchronization between the UIAbility component and UI. For example, if you bind the **want** parameter in the UIAbility component, you can use the **want** parameter information on the UI corresponding to the UIAbility component. -1. When **startAbility()** is called to start a UIAbility instance, the **onCreate()** callback is invoked, and the **want** parameter can be passed in the callback. Therefore, you can bind the **want** parameter to **globalThis**. +1. When [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called to start a UIAbility instance, the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) callback is invoked, and the **want** parameter can be passed in the callback. Therefore, you can bind the **want** parameter to **globalThis**. ```ts - import UIAbility from '@ohos.app.ability.UIAbility' + import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - onCreate(want, launch) { - globalThis.entryAbilityWant = want; - // ... - } + onCreate(want, launch) { + globalThis.entryAbilityWant = want; + ... + } - // ... + ... } ``` @@ -136,7 +133,7 @@ You can use **globalThis** to bind attributes or methods to implement data synch // Page display. build() { - // ... + ... } } ``` @@ -144,51 +141,51 @@ You can use **globalThis** to bind attributes or methods to implement data synch ### Using globalThis Between UIAbility and UIAbility -To implement data synchronization between two UIAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in AbilityA and obtain the data from AbilityB. +To implement data synchronization between two UIAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in UIAbilityA and obtain the data from UIAbilityB. -1. AbilityA stores a string and binds it to globalThis. +1. UIAbilityA stores a string and binds it to globalThis. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityA extends UIAbility { - onCreate(want, launch) { - globalThis.entryAbilityStr = 'AbilityA'; // AbilityA stores the string "AbilityA" to globalThis. - // ... - } + export default class UIAbilityA extends UIAbility { + onCreate(want, launch) { + globalThis.entryAbilityStr = 'UIAbilityA'; // UIAbilityA stores the string "UIAbilityA" to globalThis. + ... + } } ``` -2. Obtain the data from AbilityB. +2. Obtain the data from UIAbilityB. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityB extends UIAbility { - onCreate(want, launch) { - // AbilityB reads the name from globalThis and outputs it. - console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); - // ... - } + export default class UIAbilityB extends UIAbility { + onCreate(want, launch) { + // UIAbilityB reads name from globalThis and outputs it. + console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); + ... + } } ``` ### Using globalThis Between UIAbility and ExtensionAbility -To implement data synchronization between the UIAbility and ExtensionAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in AbilityA and obtain the data from ServiceExtensionAbility. +To implement data synchronization between the UIAbility and ExtensionAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in UIAbilityA and obtain the data from ServiceExtensionAbility. -1. AbilityA stores a string and binds it to globalThis. +1. UIAbilityA stores a string and binds it to globalThis. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityA extends UIAbility { - onCreate(want, launch) { - // AbilityA stores the string "AbilityA" to globalThis. - globalThis.entryAbilityStr = 'AbilityA'; - // ... - } + export default class UIAbilityA extends UIAbility { + onCreate(want, launch) { + // UIAbilityA stores the string "UIAbilityA" to globalThis. + globalThis.entryAbilityStr = 'UIAbilityA'; + ... + } } ``` @@ -198,22 +195,21 @@ To implement data synchronization between the UIAbility and ExtensionAbility com import Extension from '@ohos.app.ability.ServiceExtensionAbility' export default class ServiceExtAbility extends Extension { - onCreate(want) { - / / ServiceExtAbility reads name from globalThis and outputs it. - console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); - // ... - } + onCreate(want) { + / / ServiceExtAbility reads name from globalThis and outputs it. + console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); + ... + } } ``` ### Precautions for Using globalThis - **Figure 2** Precautions for globalThis - +**Figure 2** Precautions for globalThis ![globalThis2](figures/globalThis2.png) -- In the stage model, all the UIAbility components in a process share one ArkTS engine instance. When using **globalThis**, do not store objects with the same name. For example, if AbilityA and AbilityB use **globalThis** to store two objects with the same name, the object stored earlier will be overwritten. +- In the stage model, all the UIAbility components in a process share one ArkTS engine instance. When using **globalThis**, do not store objects with the same name. For example, if UIAbilityA and UIAbilityB use **globalThis** to store two objects with the same name, the object stored earlier will be overwritten. - This problem does not occur in the FA model because each UIAbility component uses an independent engine. @@ -221,20 +217,20 @@ To implement data synchronization between the UIAbility and ExtensionAbility com The following provides an example to describe the object overwritten problem in the stage model. -1. In the AbilityA file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis**. +1. In the UIAbilityA file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis**. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityA extends UIAbility { - onCreate(want, launch) { - globalThis.context = this.context; // AbilityA stores the context in globalThis. - // ... - } + export default class UIAbilityA extends UIAbility { + onCreate(want, launch) { + globalThis.context = this.context; // UIAbilityA stores the context in globalThis. + ... + } } ``` -2. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of Ability A. After the AbilityA instance is used, switch it to the background. +2. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of UIAbilityA. After the UIAbilityA instance is used, switch it to the background. ```ts @Entry @@ -242,33 +238,29 @@ The following provides an example to describe the object overwritten problem in struct Index { onPageShow() { let ctx = globalThis.context; // Obtain the context from globalThis and use it. - let permissions = ['com.example.permission'] - ctx.requestPermissionsFromUser(permissions,(result) => { - // ... - }); } // Page display. build() { - // ... + ... } } ``` -3. In the AbilityB file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis** and has the same name as that in the AbilityA file. +3. In the UIAbilityB file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis** and has the same name as that in the UIAbilityA file. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityB extends UIAbility { - onCreate(want, launch) { - // AbilityB overwrites the context stored by AbilityA in globalThis. - globalThis.context = this.context; - // ... - } + export default class UIAbilityB extends UIAbility { + onCreate(want, launch) { + // UIAbilityB overwrites the context stored by UIAbilityA in globalThis. + globalThis.context = this.context; + ... + } } ``` -4. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of Ability B. The obtained **globalThis.context** is the value of [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) in AbilityB. +4. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of UIAbilityB. The obtained **globalThis.context** is the value of [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) in UIAbilityB. ```ts @Entry @@ -276,47 +268,43 @@ The following provides an example to describe the object overwritten problem in struct Index { onPageShow() { let ctx = globalThis.context; // Obtain the context from globalThis and use it. - let permissions = ['com.example.permission'] - ctx.requestPermissionsFromUser(permissions,(result) => { - console.info('requestPermissionsFromUser result:' + JSON.stringify(result)); - }); } // Page display. build() { - // ... + ... } } ``` -5. Switch the AbilityB instance to the background and switch the AbilityA instance to the foreground. In this case, AbilityA will not enter the **onCreate()** lifecycle again. +5. Switch the UIAbilityB instance to the background and switch the UIAbilityA instance to the foreground. In this case, UIAbilityA will not enter the **onCreate()** lifecycle again. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityA extends UIAbility { - onCreate(want, launch) { // AbilityA will not enter this lifecycle. - globalThis.context = this.context; - // ... - } + export default class UIAbilityA extends UIAbility { + onCreate(want, launch) { // UIAbilityA will not enter this lifecycle. + globalThis.context = this.context; + ... + } } ``` -6. When the page of AbilityA is displayed, the obtained **globalThis.context** is [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) of AbilityB instead of AbilityA. An error occurs. +6. When the page of UIAbilityA is displayed, the obtained **globalThis.context** is [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) of UIAbilityB instead of UIAbilityA. An error occurs. ```ts @Entry @Component struct Index { onPageShow() { - let ctx = globalThis.context; // The context in globalThis is the context of AbilityB. - let permissions=['com.example.permission']; - ctx.requestPermissionsFromUser(permissions,(result) => { // Using this object causes a process breakdown. - console.info('requestPermissionsFromUser result:' + JSON.stringify(result)); - }); + let ctx = globalThis.context; // The context in globalThis is the context of UIAbilityB. } // Page display. build() { - // ... + ... } } ``` + +## Using AppStorage or LocalStorage for Data Synchronization + +ArkUI provides AppStorage and LocalStorage to implement application- and UIAbility-level data synchronization, respectively. Both solutions can be used to manage the application state, enhance application performance, and improve user experience. The AppStorage is a global state manager and is applicable when multiple UIAbilities share the same state data. The LocalStorage is a local state manager that manages state data used inside a single UIAbility. They help you control the application state more flexibly and improve the maintainability and scalability of applications. For details, see [State Management of Application-Level Variables](../quick-start/arkts-application-state-management-overview.md). 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 148e804f48531f286ecfe395d1ecd03464a5eb45..8e8bbb6535e1d2e0342c6e362b581ff556267ad5 100644 --- a/en/application-dev/application-models/uiability-intra-device-interaction.md +++ b/en/application-dev/application-models/uiability-intra-device-interaction.md @@ -15,6 +15,8 @@ This topic describes the UIAbility interaction modes in the following scenarios. - [Starting UIAbility of Another Application and Obtaining the Return Result](#starting-uiability-of-another-application-and-obtaining-the-return-result) +- [Starting UIAbility with Window Mode Specified (for System Applications Only)](#starting-uiability-with-window-mode-specified-for-system-applications-only) + - [Starting a Specified Page of UIAbility](#starting-a-specified-page-of-uiability) - [Using Call to Implement UIAbility Interaction (for System Applications Only)](#using-call-to-implement-uiability-interaction-for-system-applications-only) @@ -26,113 +28,134 @@ This scenario is possible when an application contains multiple UIAbility compon Assume that your application has two UIAbility components: EntryAbility and FuncAbility, either in the same module or different modules. You are required to start FuncAbility from EntryAbility. -1. In EntryAbility, call **startAbility()** to start UIAbility. The [want](../reference/apis/js-apis-app-ability-want.md) parameter is the entry parameter for starting the UIAbility instance. In the **want** parameter, **bundleName** indicates the bundle name of the application to start; **abilityName** indicates the name of the UIAbility to start; **moduleName** is required only when the target UIAbility belongs to a different module; **parameters** is used to carry custom information. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). +1. In EntryAbility, call [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start UIAbility. The [want](../reference/apis/js-apis-app-ability-want.md) parameter is the entry parameter for starting the UIAbility instance. In the **want** parameter, **bundleName** indicates the bundle name of the application to start; **abilityName** indicates the name of the UIAbility to start; **moduleName** is required only when the target UIAbility belongs to a different module; **parameters** is used to carry custom information. 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 = { - deviceId: '', // An empty deviceId indicates the local device. - bundleName: 'com.example.myapplication', - abilityName: 'FuncAbility', - moduleName: 'module1', // moduleName is optional. - parameters: {// Custom information. - info: 'From the Index page of EntryAbility', - }, + let context = ...; // UIAbilityContext + let want = { + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + moduleName: 'func', // moduleName is optional. + parameters: {// Custom information. + info: 'From the Index page of EntryAbility', + }, } - // context is the AbilityContext of the initiator UIAbility. - this.context.startAbility(wantInfo).then(() => { - // ... + // context is the UIAbilityContext of the initiator UIAbility. + context.startAbility(want).then(() => { + console.info('Succeeded in starting ability.'); }).catch((err) => { - // ... + console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); }) ``` - -2. Use the FuncAbility lifecycle callback to receive the parameters passed from EntryAbility. + +2. In FuncAbility, use [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) to receive the parameters passed in by EntryAbility. ```ts import UIAbility from '@ohos.app.ability.UIAbility'; - import Window from '@ohos.window'; export default class FuncAbility extends UIAbility { - onCreate(want, launchParam) { - // Receive the parameters passed by the initiator UIAbility. - let funcAbilityWant = want; - let info = funcAbilityWant?.parameters?.info; - // ... - } + onCreate(want, launchParam) { + // Receive the parameters passed by the initiator UIAbility. + let funcAbilityWant = want; + let info = funcAbilityWant?.parameters?.info; + ... + } } ``` - -3. To stop the **UIAbility** instance after the FuncAbility service is complete, call **terminateSelf()** in FuncAbility. + + > **NOTE** + > + > In FuncAbility started, you can obtain the PID and bundle name of the UIAbility through **parameters** in the passed **want** parameter. + +3. To stop the **UIAbility** instance after the FuncAbility service is complete, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) in FuncAbility. ```ts - // context is the AbilityContext of the UIAbility instance to stop. - this.context.terminateSelf((err) => { - // ... + let context = ...; // UIAbilityContext + + // context is the UIAbilityContext of the UIAbility instance to stop. + context.terminateSelf((err) => { + if (err.code) { + console.error(`Failed to terminate Self. Code is ${err.code}, message is ${err.message}`); + return; + } }); ``` + + > **NOTE** + > + > When [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) is called to stop the **UIAbility** instance, the snapshot of the instance is retained by default. That is, the mission corresponding to the instance is still displayed in Recents. If you do not want to retain the snapshot, set **removeMissionAfterTerminate** under the [abilities](../quick-start/module-configuration-file.md#abilities) tag to **true** in the [module.json5 file](../quick-start/module-configuration-file.md) of the corresponding UIAbility. + +4. To stop all UIAbility instances of the application, call **killProcessBySelf()** of [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md) to stop all processes of the application. ## Starting UIAbility in the Same Application and Obtaining the Return Result When starting FuncAbility from EntryAbility, you want the result to be returned after the FuncAbility service is finished. For example, your application uses two independent UIAbility components to carry the entry and sign-in functionalities. After the sign-in operation is finished in the sign-in UIAbility, the sign-in result needs to be returned to the entry UIAbility. -1. In EntryAbility, call **startAbilityForResult()** to start FuncAbility. Use **data** in the asynchronous callback to receive information returned after FuncAbility stops itself. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). +1. In EntryAbility, call [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to start FuncAbility. Use **data** in the asynchronous callback to receive information returned after FuncAbility stops itself. 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 = { - deviceId: '', // An empty deviceId indicates the local device. - bundleName: 'com.example.myapplication', - abilityName: 'FuncAbility', - moduleName: 'module1', // moduleName is optional. - parameters: {// Custom information. - info: 'From the Index page of EntryAbility', - }, + let context = ...; // UIAbilityContext + let want = { + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + moduleName: 'func', // moduleName is optional. + parameters: {// Custom information. + info: 'From the Index page of EntryAbility', + }, } - // context is the AbilityContext of the initiator UIAbility. - this.context.startAbilityForResult(wantInfo).then((data) => { - // ... + // context is the UIAbilityContext of the initiator UIAbility. + context.startAbilityForResult(want).then((data) => { + ... }).catch((err) => { - // ... + console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); }) ``` - -2. Call **terminateSelfWithResult()** to stop FuncAbility. Use the input parameter **abilityResult** to carry the information that FuncAbility needs to return to EntryAbility. + +2. Call [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to stop FuncAbility. Use the input parameter **abilityResult** to carry the information that FuncAbility needs to return to EntryAbility. ```ts + let context = ...; // UIAbilityContext const RESULT_CODE: number = 1001; let abilityResult = { - resultCode: RESULT_CODE, - want: { - bundleName: 'com.example.myapplication', - abilityName: 'FuncAbility', - moduleName: 'module1', - parameters: { - info: 'From the Index page of FuncAbility', - }, + resultCode: RESULT_CODE, + want: { + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + moduleName: 'func', + parameters: { + info: 'From the Index page of FuncAbility', }, + }, } // context is the AbilityContext of the target UIAbility. - this.context.terminateSelfWithResult(abilityResult, (err) => { - // ... + context.terminateSelfWithResult(abilityResult, (err) => { + if (err.code) { + console.error(`Failed to terminate self with result. Code is ${err.code}, message is ${err.message}`); + return; + } }); ``` - -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. + +3. After FuncAbility stops itself, EntryAbility uses [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to receive the information returned by FuncAbility. The value of **RESULT_CODE** must be the same as the preceding value. ```ts + let context = ...; // UIAbilityContext const RESULT_CODE: number = 1001; - // ... + ... - // context is the AbilityContext of the initiator UIAbility. - this.context.startAbilityForResult(want).then((data) => { - if (data?.resultCode === RESULT_CODE) { - // Parse the information returned by the target UIAbility. - let info = data.want?.parameters?.info; - // ... - } + // context is the UIAbilityContext of the initiator UIAbility. + context.startAbilityForResult(want).then((data) => { + if (data?.resultCode === RESULT_CODE) { + // Parse the information returned by the target UIAbility. + let info = data.want?.parameters?.info; + ... + } }).catch((err) => { - // ... + console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); }) ``` @@ -145,26 +168,26 @@ There are two ways to start **UIAbility**: [explicit and implicit](want-overview - 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 **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. +- 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()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the want parameter specifies a series of parameters such as **entities** and **actions**. **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. -1. Install multiple document applications on your device. In the **module.json5** file of each UIAbility component, configure [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) under **skills**. +1. Install multiple document applications on your device. In the [module.json5 file](../quick-start/module-configuration-file.md) of each UIAbility component, configure **entities** and **actions** under **skills**. ```json { "module": { "abilities": [ { - // ... + ... "skills": [ { "entities": [ - // ... + ... "entity.system.default" ], "actions": [ - // ... + ... "ohos.want.action.viewData" ] } @@ -178,57 +201,62 @@ This section describes how to start the UIAbility of another application through 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 = { - deviceId: '', // An empty deviceId indicates the local device. - // 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.default'], + let context = ...; // UIAbilityContext + let want = { + deviceId: '', // An empty deviceId indicates the local device. + // 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.default'], } - // context is the AbilityContext of the initiator UIAbility. - this.context.startAbility(wantInfo).then(() => { - // ... + // context is the UIAbilityContext of the initiator UIAbility. + context.startAbility(want).then(() => { + console.info('Succeeded in starting ability.'); }).catch((err) => { - // ... + console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); }) ``` - - The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select. - - ![uiability-intra-device-interaction](figures/uiability-intra-device-interaction.png) -3. To stop the **UIAbility** instance after the document application is used, call **terminateSelf()**. + The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select. + ![](figures/uiability-intra-device-interaction.png) + +3. To stop the **UIAbility** instance after the document application is used, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself). ```ts - // context is the AbilityContext of the UIAbility instance to stop. - this.context.terminateSelf((err) => { - // ... + let context = ...; // UIAbilityContext + + // context is the UIAbilityContext of the UIAbility instance to stop. + context.terminateSelf((err) => { + if (err.code) { + console.error(`Failed to terminate self. Code is ${err.code}, message is ${err.message}`); + return; + } }); ``` ## 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 **startAbilityForResult()**. 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()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult). An example scenario is that the main application needs to start a third-party payment application and obtain the payment result. -1. In the **module.json5** file of the UIAbility corresponding to the payment application, set [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) under **skills**. +1. In the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility corresponding to the payment application, set **entities** and **actions** under **skills**. ```json { "module": { "abilities": [ { - // ... + ... "skills": [ { "entities": [ - // ... + ... "entity.system.default" ], "actions": [ - // ... + ... "ohos.want.action.editData" ] } @@ -239,68 +267,125 @@ If you want to obtain the return result when using implicit Want to start the UI } ``` -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. +2. Call [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) 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 = { - deviceId: '', // An empty deviceId indicates the local device. - // Uncomment the line below if you want to implicitly query data only in the specific bundle. - // bundleName: 'com.example.myapplication', - action: 'ohos.want.action.editData', - // entities can be omitted. - entities: ['entity.system.default'], + let context = ...; // UIAbilityContext + let want = { + deviceId: '', // An empty deviceId indicates the local device. + // Uncomment the line below if you want to implicitly query data only in the specific bundle. + // bundleName: 'com.example.myapplication', + action: 'ohos.want.action.editData', + // entities can be omitted. + entities: ['entity.system.default'] } - // context is the AbilityContext of the initiator UIAbility. - this.context.startAbilityForResult(wantInfo).then((data) => { - // ... + // context is the UIAbilityContext of the initiator UIAbility. + context.startAbilityForResult(want).then((data) => { + ... }).catch((err) => { - // ... + console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); }) ``` - -3. After the payment is finished, call **terminateSelfWithResult()** to stop the payment UIAbility and return the **abilityResult** parameter. + +3. After the payment is finished, call [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to stop the payment UIAbility and return the **abilityResult** parameter. ```ts + let context = ...; // UIAbilityContext const RESULT_CODE: number = 1001; let abilityResult = { - resultCode: RESULT_CODE, - want: { - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', - moduleName: 'entry', - parameters: { - payResult: 'OKay', - }, + resultCode: RESULT_CODE, + want: { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + moduleName: 'entry', + parameters: { + payResult: 'OKay', }, + }, } // context is the AbilityContext of the target UIAbility. - this.context.terminateSelfWithResult(abilityResult, (err) => { - // ... + context.terminateSelfWithResult(abilityResult, (err) => { + if (err.code) { + console.error(`Failed to terminate self with result. Code is ${err.code}, message is ${err.message}`); + return; + } }); ``` - -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()**. + +4. Receive the information returned by the payment application in the callback of the [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) method. The value of **RESULT_CODE** must be the same as that returned by [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult). ```ts + let context = ...; // UIAbilityContext const RESULT_CODE: number = 1001; let want = { // Want parameter information. }; - // context is the AbilityContext of the initiator UIAbility. - this.context.startAbilityForResult(want).then((data) => { - if (data?.resultCode === RESULT_CODE) { - // Parse the information returned by the target UIAbility. - let payResult = data.want?.parameters?.payResult; - // ... - } + // context is the UIAbilityContext of the initiator UIAbility. + context.startAbilityForResult(want).then((data) => { + if (data?.resultCode === RESULT_CODE) { + // Parse the information returned by the target UIAbility. + let payResult = data.want?.parameters?.payResult; + ... + } }).catch((err) => { - // ... + console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); }) ``` +## Starting UIAbility with Window Mode Specified (for System Applications Only) + +By specifying the window mode when starting the UIAbility of an application, the application can be displayed in different window modes, which can be full-screen, floating window, or split-screen. + +In full-screen mode, an application occupies the entire screen after being started. Users cannot view other windows or applications. This mode is suitable for an application that requires users to focus on a specific task or UI. + +In floating window mode, an application is displayed on the screen as a floating window after being started. Users can easily switch to other windows or applications. The mode is suitable for an application that requires users to process multiple tasks at the same time. + +In split-screen mode, two applications occupy the entire screen, with one on the left or in the upper part of the screen and the other on the right or in the lower part. This mode helps users improve multi-task processing efficiency. + +The window mode is specified by the **windowMode** field in the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter of [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability). + +> **NOTE** +> +> 1. If the **windowMode** field is not specified, the UIAbility is started in the default window mode. +> 2. To ensure that the application can be displayed in the required window mode, check the **supportWindowMode** field in the [abilities](../quick-start/module-configuration-file.md#abilities) tag in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility and make sure the specified window mode is supported. + +The following uses the floating window mode as an example to describe how to start the FuncAbility from the EntryAbility page. + +1. Add the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability). +2. Set the **windowMode** field in the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter to **WINDOW_MODE_FLOATING**, indicating that the UIAbility will be displayed in a floating window. + +For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). + +```ts +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + +let context = ...; // UIAbilityContext +let want = { + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + moduleName: 'func', // moduleName is optional. + parameters: {// Custom information. + info: 'From the Index page of EntryAbility', + }, +} +let options = { + windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FLOATING +}; +// context is the UIAbilityContext of the initiator UIAbility. +context.startAbility(want, options).then(() => { + console.info('Succeeded in starting ability.'); +}).catch((err) => { + console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); +}) +``` + +The display effect is shown below. + +![](figures/start-uiability-floating-window.png) ## Starting a Specified Page of UIAbility @@ -313,20 +398,21 @@ When the initiator UIAbility starts another UIAbility, it usually needs to redir ```ts -let wantInfo = { +let context = ...; // UIAbilityContext +let want = { deviceId: '', // An empty deviceId indicates the local device. bundleName: 'com.example.myapplication', abilityName: 'FuncAbility', - moduleName: 'module1', // moduleName is optional. + moduleName: 'func', // moduleName is optional. parameters: {// Custom parameter used to pass the page information. router: 'funcA', }, } -// context is the AbilityContext of the initiator UIAbility. -this.context.startAbility(wantInfo).then(() => { - // ... +// context is the UIAbilityContext of the initiator UIAbility. +context.startAbility(want).then(() => { + console.info('Succeeded in starting ability.'); }).catch((err) => { - // ... + console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); }) ``` @@ -341,25 +427,25 @@ import UIAbility from '@ohos.app.ability.UIAbility' import Window from '@ohos.window' export default class FuncAbility extends UIAbility { - funcAbilityWant; - - onCreate(want, launchParam) { - // 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 UIAbility. - let url = 'pages/Index'; - if (this.funcAbilityWant?.parameters?.router) { - if (this.funcAbilityWant.parameters.router === 'funA') { - url = 'pages/Second'; - } - } - windowStage.loadContent(url, (err, data) => { - // ... - }); + funcAbilityWant; + + onCreate(want, launchParam) { + // 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 UIAbility. + let url = 'pages/Index'; + if (this.funcAbilityWant?.parameters?.router) { + if (this.funcAbilityWant.parameters.router === 'funA') { + url = 'pages/Second'; + } } + windowStage.loadContent(url, (err, data) => { + ... + }); + } } ``` @@ -378,11 +464,11 @@ In summary, when a UIAbility instance of application A has been created and the import UIAbility from '@ohos.app.ability.UIAbility' export default class FuncAbility extends UIAbility { - onNewWant(want, launchParam) { - // Receive the parameters passed by the initiator UIAbility. - globalThis.funcAbilityWant = want; - // ... - } + onNewWant(want, launchParam) { + // Receive the parameters passed by the initiator UIAbility. + globalThis.funcAbilityWant = want; + ... + } } ``` @@ -406,25 +492,25 @@ In summary, when a UIAbility instance of application A has been created and the // Page display. build() { - // ... + ... } } ``` > **NOTE** > -> 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. +> When the [launch type of the target UIAbility](uiability-launch-type.md) is set to **multiton**, 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 Call to Implement UIAbility Interaction (for System Applications Only) 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 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 UIAbility launch in the foreground and background, whereas **startAbility** supports UIAbility launch in the foreground only. +- **startAbilityByCall()** supports UIAbility launch in the foreground and background, whereas **startAbility()** supports UIAbility launch in the foreground only. -- The CallerAbility can use the caller object returned by **startAbilityByCall** to communicate with the CalleeAbility, 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. Call is usually used in the following scenarios: @@ -432,20 +518,21 @@ Call is usually used in the following scenarios: - Starting the CalleeAbility in the background + **Table 1** Terms used in the call | **Term**| Description| | -------- | -------- | -| CallerAbility | UIAbility that triggers the call.| +| 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 call process. - Figure 1 Call process +Figure 1 Call process - ![call](figures/call.png) +![call](figures/call.png) - The CallerAbility uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the CalleeAbility. @@ -463,7 +550,7 @@ The following figure shows the call process. 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** Call APIs +**Table 2** Call APIs | API| Description| | -------- | -------- | @@ -487,32 +574,13 @@ The implementation of using the call for UIAbility interaction involves two part 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 CalleeAbility to **singleton** in the **module.json5** file. - - | JSON Field| Description| - | -------- | -------- | - | "launchType" | Ability launch type. Set this parameter to **singleton**.| - - An example of the ability configuration is as follows: - - ```json - "abilities":[{ - "name": ".CalleeAbility", - "srcEnty": "./ets/CalleeAbility/CalleeAbility.ts", - "launchType": "singleton", - "description": "$string:CalleeAbility_desc", - "icon": "$media:icon", - "label": "$string:CalleeAbility_label", - "exported": true - }] - ``` - + For example, set the launch type of the CalleeAbility to **singleton**. For details, see [UIAbility Component Launch Type](uiability-launch-type.md). + 2. Import the **UIAbility** module. ```ts - import Ability from '@ohos.app.ability.UIAbility'; + import UIAbility from '@ohos.app.ability.UIAbility'; ``` 3. Define the agreed parcelable data. @@ -522,66 +590,66 @@ For the CalleeAbility, implement the callback to receive data and the methods to ```ts export default class MyParcelable { - num: number = 0 - str: string = "" + num: number = 0; + str: string = ''; - constructor(num, string) { - this.num = num - this.str = string - } + constructor(num, string) { + this.num = num; + this.str = string; + } - marshalling(messageSequence) { - messageSequence.writeInt(this.num) - messageSequence.writeString(this.str) - return true - } + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); + return true; + } - unmarshalling(messageSequence) { - this.num = messageSequence.readInt() - this.str = messageSequence.readString() - return true - } + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); + return true; + } } ``` 4. Implement **Callee.on** and **Callee.off**. - + 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 const TAG: string = '[CalleeAbility]'; const MSG_SEND_METHOD: string = 'CallSendMsg'; function sendMsgCallback(data) { - console.info('CalleeSortFunc called'); + console.info('CalleeSortFunc called'); - // Obtain the parcelable data sent by the CallerAbility. - let receivedData = new MyParcelable(0, ''); - data.readParcelable(receivedData); - console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); + // 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 CallerAbility. - return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`); + // Process the data. + // Return the parcelable data result to the CallerAbility. + return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`); } - export default class CalleeAbility extends Ability { - onCreate(want, launchParam) { - try { - this.callee.on(MSG_SEND_METHOD, sendMsgCallback); - } catch (error) { - console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`); - } + export default class CalleeAbility extends UIAbility { + onCreate(want, launchParam) { + try { + this.callee.on(MSG_SEND_METHOD, sendMsgCallback); + } catch (err) { + console.error(`Failed to register. Code is ${err.code}, message is ${err.message}`); } + } - onDestroy() { - try { - this.callee.off(MSG_SEND_METHOD); - } catch (error) { - console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`); - } + onDestroy() { + try { + this.callee.off(MSG_SEND_METHOD); + } catch (err) { + console.error(`Failed to unregister. Code is ${err.code}, message is ${err.message}`); } + } } ``` @@ -591,41 +659,41 @@ For the CalleeAbility, implement the callback to receive data and the methods to 1. Import the **UIAbility** module. ```ts - import Ability from '@ohos.app.ability.UIAbility'; + import UIAbility from '@ohos.app.ability.UIAbility'; ``` 2. Obtain the caller interface. - 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. + 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 CallerAbility. private regOnRelease(caller) { - try { - caller.on("release", (msg) => { - console.info(`caller onRelease is called ${msg}`); - }) - console.info('caller register OnRelease succeed'); - } catch (error) { - console.info(`caller register OnRelease failed with ${error}`); - } + try { + caller.on('release', (msg) => { + console.info(`caller onRelease is called ${msg}`); + }) + console.info('Succeeded in registering on release.'); + } catch (err) { + console.err(`Failed to caller register on release. Code is ${err.code}, message is ${err.message}`); + } } async onButtonGetCaller() { - try { - this.caller = await context.startAbilityByCall({ - bundleName: 'com.samples.CallApplication', - abilityName: 'CalleeAbility' - }) - if (this.caller === undefined) { - console.info('get caller failed') - return - } - console.info('get caller success') - this.regOnRelease(this.caller) - } catch (error) { - console.info(`get caller failed with ${error}`) + try { + this.caller = await context.startAbilityByCall({ + bundleName: 'com.samples.CallApplication', + abilityName: 'CalleeAbility' + }); + if (this.caller === undefined) { + console.info('get caller failed') + return; } + console.info('get caller success') + this.regOnRelease(this.caller) + } (err) { + console.err(`Failed to get caller. Code is ${err.code}, message is ${err.message}`); + } } ``` diff --git a/en/application-dev/application-models/uiability-launch-type.md b/en/application-dev/application-models/uiability-launch-type.md index ff904d4f60918a5ceed622840d5a153e52f8d1a4..c7aac3d4bc3acdb2601580646024ec1f8117473f 100644 --- a/en/application-dev/application-models/uiability-launch-type.md +++ b/en/application-dev/application-models/uiability-launch-type.md @@ -17,7 +17,8 @@ The launch type of the UIAbility component refers to the state of the UIAbility Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, if a UIAbility instance of this type already exists in the application process, the instance is reused. Therefore, only one UIAbility instance of this type exists in the system, that is, displayed in **Recents**. -**Figure 1** Demonstration effect in singleton mode +**Figure 1** Demonstration effect in singleton mode + ![uiability-launch-type1](figures/uiability-launch-type1.gif) > **NOTE** @@ -30,11 +31,11 @@ To use the singleton mode, set **launchType** in the [module.json5 configuration ```json { "module": { - // ... + ... "abilities": [ { "launchType": "singleton", - // ... + ... } ] } @@ -56,11 +57,11 @@ To use the multiton mode, set **launchType** in the [module.json5 file](../quick ```json { "module": { - // ... + ... "abilities": [ { "launchType": "multiton", - // ... + ... } ] } @@ -73,6 +74,7 @@ To use the multiton mode, set **launchType** in the [module.json5 file](../quick The **specified** mode is used in some special scenarios. For example, in a document application, you want a document instance to be created each time you create a document, but you want to use the same document instance when you repeatedly open an existing document. **Figure 3** Demonstration effect in specified mode + ![uiability-launch-type3](figures/uiability-launch-type3.gif) For example, there are two UIAbility components: EntryAbility and SpecifiedAbility (with the launch type **specified**). You are required to start SpecifiedAbility from EntryAbility. @@ -82,11 +84,11 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili ```json { "module": { - // ... + ... "abilities": [ { "launchType": "specified", - // ... + ... } ] } @@ -99,23 +101,24 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili // Configure an independent key for each UIAbility instance. // For example, in the document usage scenario, use the document path as the key. function getInstance() { - // ... + ... } + let context =...; // context is the UIAbilityContext of the initiator UIAbility. let want = { - deviceId: '', // An empty deviceId indicates the local device. - bundleName: 'com.example.myapplication', - abilityName: 'SpecifiedAbility', - moduleName: 'module1', // moduleName is optional. - parameters: {// Custom information. - instanceKey: getInstance(), - }, + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'SpecifiedAbility', + moduleName: 'specified', // moduleName is optional. + parameters: {// Custom information. + instanceKey: getInstance(), + }, } - // context is the UIAbilityContext of the initiator UIAbility. - this.context.startAbility(want).then(() => { - // ... + + context.startAbility(want).then(() => { + console.info('Succeeded in starting ability.'); }).catch((err) => { - // ... + console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); }) ``` @@ -127,16 +130,16 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili import AbilityStage from '@ohos.app.ability.AbilityStage'; export default class MyAbilityStage extends AbilityStage { - onAcceptWant(want): string { - // 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 key string is a custom string. - return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`; - } - - return ''; + onAcceptWant(want): string { + // 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 key string is a custom string. + return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`; } + + return ''; + } } ``` @@ -153,3 +156,4 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili 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. This is because the system automatically matches the key of the UIAbility instance and starts the UIAbility instance that has a matching key. In this example, UIAbility instance 2 has the same key as file A. Therefore, the system pulls back UIAbility instance 2 and focuses it without creating a new instance. + diff --git a/en/application-dev/application-models/uiability-lifecycle.md b/en/application-dev/application-models/uiability-lifecycle.md index 57200abb8fbfb625e2e6c8999da5ad817e2e85b4..a61b9ae836904a420877d4d36ad011f82cf5202b 100644 --- a/en/application-dev/application-models/uiability-lifecycle.md +++ b/en/application-dev/application-models/uiability-lifecycle.md @@ -8,8 +8,7 @@ When a user opens, switches, and returns to an application, the UIAbility instan The lifecycle of UIAbility has four states: **Create**, **Foreground**, **Background**, and **Destroy**, as shown in the figure below. **Figure 1** UIAbility lifecycle states - -![Ability-Life-Cycle](figures/Ability-Life-Cycle.png) +![Ability-Life-Cycle](figures/Ability-Life-Cycle.png) ## Description of Lifecycle States @@ -22,24 +21,25 @@ The **Create** state is triggered when the UIAbility instance is created during ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - // Initialize the application. - } - // ... + onCreate(want, launchParam) { + // Initialize the application. + } + ... } ``` +> **NOTE** +> +> [Want](../reference/apis/js-apis-app-ability-want.md) is used as the carrier to transfer information between application components. For details, see [Want](want-overview.md). ### WindowStageCreate and WindowStageDestory After the UIAbility instance is created but before it enters the **Foreground** state, the system creates a WindowStage instance and triggers the **onWindowStageCreate()** callback. You can set UI loading and WindowStage event subscription in the callback. -**Figure 2** WindowStageCreate and WindowStageDestory - -![Ability-Life-Cycle-WindowStage](figures/Ability-Life-Cycle-WindowStage.png) +**Figure 2** WindowStageCreate and WindowStageDestory +![Ability-Life-Cycle-WindowStage](figures/Ability-Life-Cycle-WindowStage.png) In the **onWindowStageCreate()** callback, use [loadContent()](../reference/apis/js-apis-window.md#loadcontent9-2) to set the page to be loaded, and call [on('windowStageEvent')](../reference/apis/js-apis-window.md#onwindowstageevent9) to subscribe to [WindowStage events](../reference/apis/js-apis-window.md#windowstageeventtype9), for example, having or losing focus, or becoming visible or invisible. @@ -48,25 +48,40 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - // ... - - onWindowStageCreate(windowStage: Window.WindowStage) { - // Subscribe to the WindowStage events (having or losing focus, or becoming visible or invisible). - try { - windowStage.on('windowStageEvent', (data) => { - console.info('Succeeded in enabling the listener for window stage event changes. Data: ' + - JSON.stringify(data)); - }); - } catch (exception) { - console.error('Failed to enable the listener for window stage event changes. Cause:' + - JSON.stringify(exception)); - }; - - // Set the UI loading. - windowStage.loadContent('pages/Index', (err, data) => { - // ... - }); + ... + + onWindowStageCreate(windowStage: window.WindowStage) { + // Subscribe to the WindowStage events (having or losing focus, or becoming visible or invisible). + try { + windowStage.on('windowStageEvent', (data) => { + let stageEventType: window.WindowStageEventType = data; + switch (stageEventType) { + case window.WindowStageEventType.SHOWN: // Switch to the foreground. + console.info('windowStage foreground.'); + break; + case window.WindowStageEventType.ACTIVE: // Gain focus. + console.info('windowStage active.'); + break; + case window.WindowStageEventType.INACTIVE: // Lose focus. + console.info('windowStage inactive.'); + break; + case window.WindowStageEventType.HIDDEN: // Switch to the background. + console.info('windowStage background.'); + break; + default: + break; + } + }); + } catch (exception) { + console.error('Failed to enable the listener for window stage event changes. Cause:' + + JSON.stringify(exception)); } + + // Set UI loading. + windowStage.loadContent('pages/Index', (err, data) => { + ... + }); + } } ``` @@ -82,18 +97,23 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - // ... - - onWindowStageDestroy() { - // Release UI resources. - // Unsubscribe from the WindowStage events such as having or losing focus in the onWindowStageDestroy() callback. - try { - windowStage.off('windowStageEvent'); - } catch (exception) { - console.error('Failed to disable the listener for window stage event changes. Cause:' + - JSON.stringify(exception)); - }; - } + windowStage: window.WindowStage; + ... + + onWindowStageCreate(windowStage: window.WindowStage) { + this.windowStage = windowStage; + ... + } + + onWindowStageDestroy() { + // Release UIresources. + // Unsubscribe from the WindowStage events such as having or losing focus in the onWindowStageDestroy() callback. + try { + this.windowStage.off('windowStageEvent'); + } catch (err) { + console.error(`Failed to disable the listener for window stage event changes. Code is ${err.code}, message is ${err.message}`); + }; + } } ``` @@ -115,16 +135,16 @@ When the application is switched to the background, you can disable positioning import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - // ... + ... - onForeground() { - // Apply for the resources required by the system or re-apply for the resources released in onBackground(). - } + onForeground() { + // Apply for the resources required by the system or re-apply for the resources released in onBackground(). + } - onBackground() { - // Release useless resources when the UI is invisible, or perform time-consuming operations in this callback, - // for example, saving the status. - } + onBackground() { + // Release useless resources when the UI is invisible, or perform time-consuming operations in this callback, + // for example, saving the status. + } } ``` @@ -137,13 +157,12 @@ The UIAbility instance is destroyed when **terminateSelf()** is called or the us ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - // ... + ... - onDestroy() { - // Release system resources and save data. - } + onDestroy() { + // Release system resources and save data. + } } ``` diff --git a/en/application-dev/application-models/uiability-overview.md b/en/application-dev/application-models/uiability-overview.md index 7862f2038fc6c353629bcdc9b3e51cfb5bedb046..5aa0ca79c49bd9f7566e7e0cc1ea977cea8c83d5 100644 --- a/en/application-dev/application-models/uiability-overview.md +++ b/en/application-dev/application-models/uiability-overview.md @@ -11,7 +11,9 @@ The following design philosophy is behind UIAbility: 2. Support for multiple device types and window forms -For details, see [Interpretation of the Application Model](application-model-description.md). +> **NOTE** +> +> For details, see [Interpretation of the Application Model](application-model-description.md). The UIAbility division principles and suggestions are as follows: @@ -33,17 +35,17 @@ To enable an application to properly use a UIAbility component, declare the UIAb ```json { "module": { - // ... + ... "abilities": [ { "name": "EntryAbility", // Name of the UIAbility component. - "srcEnty": "./ets/entryability/EntryAbility.ts", // Code path of the UIAbility component. + "srcEntry": "./ets/entryability/EntryAbility.ts", // Code path of the UIAbility component. "description": "$string:EntryAbility_desc", // Description of the UIAbility component. "icon": "$media:icon", // Icon of the UIAbility component. "label": "$string:EntryAbility_label", // Label of the UIAbility component. "startWindowIcon": "$media:icon", // Index of the icon resource file. "startWindowBackground": "$color:start_window_background", // Index of the background color resource file. - // ... + ... } ] } diff --git a/en/application-dev/application-models/uiability-usage.md b/en/application-dev/application-models/uiability-usage.md index fa8badc6d48c7e550922cb60a15d02eab9cc80b6..46959284ef3bfe179d465f5dae92b6f8538f680a 100644 --- a/en/application-dev/application-models/uiability-usage.md +++ b/en/application-dev/application-models/uiability-usage.md @@ -14,14 +14,14 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage: window.WindowStage) { - // Main window is created. Set a main page for this ability. - windowStage.loadContent('pages/Index', (err, data) => { - // ... - }); - } + onWindowStageCreate(windowStage: window.WindowStage) { + // Main window is created. Set a main page for this ability. + windowStage.loadContent('pages/Index', (err, data) => { + ... + }); + } - // ... + ... } ``` @@ -40,15 +40,14 @@ The UIAbility class has its own context, which is an instance of the [UIAbilityC import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - // Obtain the context of the UIAbility instance. - let context = this.context; - - // ... - } + onCreate(want, launchParam) { + // Obtain the context of the UIAbility instance. + let context = this.context; + ... + } } ``` - + - Import the context module and define the **context** variable in the component. ```ts @@ -68,7 +67,7 @@ The UIAbility class has its own context, which is an instance of the [UIAbilityC // Page display. build() { - // ... + ... } } ``` @@ -93,7 +92,7 @@ The UIAbility class has its own context, which is an instance of the [UIAbilityC // Page display. build() { - // ... + ... } } ``` diff --git a/en/application-dev/application-models/want-overview.md b/en/application-dev/application-models/want-overview.md index 21c79d517fc237cae9b9bab7d5347ffc82766d5a..cf5cac43999a5efbe59659252b6b3db325cacd8a 100644 --- a/en/application-dev/application-models/want-overview.md +++ b/en/application-dev/application-models/want-overview.md @@ -3,47 +3,49 @@ ## Definition and Usage of Want -[Want](../reference/apis/js-apis-app-ability-want.md) is used as the carrier to transfer information between application components. It is used as a parameter of **startAbility()** to specify the startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. For example, when UIAbilityA starts UIAbilityB and needs to transfer some data to UIAbilityB, it can use Want to transfer the data. +[Want](../reference/apis/js-apis-app-ability-want.md) is an object that transfers information between application components. It is often used as a parameter of [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability). For example, when UIAbilityA needs to start UIAbilityB and transfer some data to UIAbilityB, it can use the **want** parameter in **startAbility()** to transfer the data. -**Figure 1** Want usage +**Figure 1** Want usage -![usage-of-want](figures/usage-of-want.png) +![usage-of-want](figures/usage-of-want.png) ## Types of Want -- **Explicit Want**: A type of Want with **abilityName** and **bundleName** specified when starting an ability. - When there is an explicit object to process the request, the target ability can be started by specifying the bundle name and ability name in Want. Explicit Want is usually used to start a known ability. - +- **Explicit Want**: If **abilityName** and **bundleName** are specified in the **want** parameter when starting an an application component, explicit Want is used. + + Explicit Want is usually used to start a known target application component in the same application. The target application component is started by specifying **bundleName** of the application where the target application component is located and **abilityName** in the **Want** object. When there is an explicit object to process the request, explicit Want is a simple and effective way to start the target application component. + ```ts let wantInfo = { - deviceId: '', // An empty deviceId indicates the local device. - bundleName: 'com.example.myapplication', - abilityName: 'FuncAbility', + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', } ``` - -- **Implicit Want**: A type of Want with **abilityName** unspecified when starting the ability. - Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills)) provided by another application. For example, you can use implicit Want to describe a request for opening a link, since you do not care which application is used to open the link. The system matches all applications that support the request. - + +- **Implicit Want**: If **abilityName** is not specified in the **want** parameter when starting the an application component, implicit Want is used. + + Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills)) provided by another application. The system matches all applications that declare to support the capability. For example, for a link open request, the system matches all applications that support the request and provides the available ones for users to select. + ```ts 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.search', - // entities can be omitted. - entities: [ 'entity.system.browsable' ], - uri: 'https://www.test.com:8080/query/student', - type: 'text/plain', + // Uncomment the line below if you want to implicitly query data only in the specific bundle. + // bundleName: 'com.example.myapplication', + action: 'ohos.want.action.search', + // entities can be omitted. + entities: [ 'entity.system.browsable' ], + uri: 'https://www.test.com:8080/query/student', + type: 'text/plain', }; ``` - + > **NOTE** - > - Depending on the ability matching result, the following cases may be possible when you attempt to use implicit Want to start the ability. - > - No ability is matched. The startup fails. - > - An ability that meets the conditions is matched. That ability is started. - > - Multiple abilities that meet the conditions are matched. A dialog box is displayed for users to select one of them. + > - Depending on the application component matching result, the following cases may be possible when you attempt to use implicit Want to start the application component. + > - No application component is matched. The startup fails. + > - An application component that meets the conditions is matched. That application component is started. + > - Multiple application components that meet the conditions are matched. A dialog box is displayed for users to select one of them. > > - If the **want** parameter passed does not contain **abilityName** or **bundleName**, the ServiceExtensionAbility components of all applications cannot be started through implicit Want. > diff --git a/en/application-dev/application-models/widget-development-fa.md b/en/application-dev/application-models/widget-development-fa.md index 73cf20e0ce6ab82ae9e775dd8fb8f43922218b48..3aa1a9fd29495b36a02d155e5d2ad48e94bce5ad 100644 --- a/en/application-dev/application-models/widget-development-fa.md +++ b/en/application-dev/application-models/widget-development-fa.md @@ -20,7 +20,7 @@ Before you get started, it would be helpful if you have a basic understanding of Figure 1 shows the working principles of the widget framework. -**Figure 1** Widget framework working principles in the FA model +**Figure 1** Widget framework working principles in the FA model ![form-extension](figures/form-extension.png) The widget host consists of the following modules: @@ -122,48 +122,48 @@ To create a widget in the FA model, implement the widget lifecycle callbacks. Ge ```ts export default { - onCreate(want) { - console.info('FormAbility onCreate'); - // Called when the widget is created. The widget provider should return the widget data binding class. - let obj = { - "title": "titleOnCreate", - "detail": "detailOnCreate" - }; - let formData = formBindingData.createFormBindingData(obj); - return formData; - }, - onCastToNormal(formId) { - // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. - console.info('FormAbility onCastToNormal'); - }, - onUpdate(formId) { - // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. - console.info('FormAbility onUpdate'); - let obj = { - "title": "titleOnUpdate", - "detail": "detailOnUpdate" - }; - let formData = formBindingData.createFormBindingData(obj); - formProvider.updateForm(formId, formData).catch((error) => { - console.info('FormAbility updateForm, error:' + JSON.stringify(error)); - }); - }, - onVisibilityChange(newStatus) { - // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification. This callback takes effect only for system applications. - console.info('FormAbility onVisibilityChange'); - }, - onEvent(formId, message) { - // If the widget supports event triggering, override this method and implement the trigger. - console.info('FormAbility onEvent'); - }, - onDestroy(formId) { - // Delete widget data. - console.info('FormAbility onDestroy'); - }, - onAcquireFormState(want) { - console.info('FormAbility onAcquireFormState'); - return formInfo.FormState.READY; - }, + onCreate(want) { + console.info('FormAbility onCreate'); + // Called when the widget is created. The widget provider should return the widget data binding class. + let obj = { + "title": "titleOnCreate", + "detail": "detailOnCreate" + }; + let formData = formBindingData.createFormBindingData(obj); + return formData; + }, + onCastToNormal(formId) { + // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. + console.info('FormAbility onCastToNormal'); + }, + onUpdate(formId) { + // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. + console.info('FormAbility onUpdate'); + let obj = { + "title": "titleOnUpdate", + "detail": "detailOnUpdate" + }; + let formData = formBindingData.createFormBindingData(obj); + formProvider.updateForm(formId, formData).catch((error) => { + console.info('FormAbility updateForm, error:' + JSON.stringify(error)); + }); + }, + onVisibilityChange(newStatus) { + // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification. This callback takes effect only for system applications. + console.info('FormAbility onVisibilityChange'); + }, + onEvent(formId, message) { + // If the widget supports event triggering, override this method and implement the trigger. + console.info('FormAbility onEvent'); + }, + onDestroy(formId) { + // Delete widget data. + console.info('FormAbility onDestroy'); + }, + onAcquireFormState(want) { + console.info('FormAbility onAcquireFormState'); + return formInfo.FormState.READY; + }, } ``` @@ -188,15 +188,15 @@ The widget configuration file is named **config.json**. Find the **config.json** ```json - "js": [{ - "name": "widget", - "pages": ["pages/index/index"], - "window": { - "designWidth": 720, - "autoDesignWidth": true - }, - "type": "form" - }] + "js": [{ + "name": "widget", + "pages": ["pages/index/index"], + "window": { + "designWidth": 720, + "autoDesignWidth": true + }, + "type": "form" + }] ``` - The **abilities** module in the **config.json** file corresponds to **FormAbility** of the widget. The internal structure is described as follows: @@ -232,7 +232,7 @@ The widget configuration file is named **config.json**. Find the **config.json** "type": "service", "srcLanguage": "ets", "formsEnabled": true, - "formConfigAbility": "ability://com.example.entry.MainAbility", + "formConfigAbility": "ability://com.example.entry.EntryAbility", "forms": [{ "colorMode": "auto", "defaultDimension": "2*2", @@ -275,7 +275,7 @@ async function storeFormInfo(formId: string, formName: string, tempFlag: boolean } } -// ... +... onCreate(want) { console.info('FormAbility onCreate'); @@ -293,7 +293,7 @@ async function storeFormInfo(formId: string, formName: string, tempFlag: boolean let formData = formBindingData.createFormBindingData(obj); return formData; } -// ... +... ``` You should override **onDestroy** to implement widget data deletion. @@ -313,14 +313,14 @@ async function deleteFormInfo(formId: string) { } } -// ... +... onDestroy(formId) { console.info('FormAbility onDestroy'); // Delete the persistent widget instance data. // Implement this API based on project requirements. deleteFormInfo(formId); } -// ... +... ``` For details about how to implement persistent data storage, see [Application Data Persistence Overview](../database/app-data-persistence-overview.md). @@ -434,7 +434,7 @@ You can use the web-like paradigm (HML+CSS+JSON) to develop JS widget pages. Thi "actions": { "routerEvent": { "action": "router", - "abilityName": "com.example.entry.MainAbility", + "abilityName": "com.example.entry.EntryAbility", "params": { "message": "add detail" } @@ -452,8 +452,8 @@ You can set router and message events for components on a widget. The router eve 2. Set the router event. - **action**: **"router"**, which indicates a router event. - - **abilityName**: name of the ability to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name created by DevEco Studio in the FA model is com.example.entry.MainAbility. - - **params**: custom parameters passed to the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the MainAbility in the FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field. + - **abilityName**: name of the ability to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name created by DevEco Studio in the FA model is com.example.entry.EntryAbility. + - **params**: custom parameters passed to the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the EntryAbility in the FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field. 3. Set the message event. - **action**: **"message"**, which indicates a message event. @@ -529,7 +529,7 @@ The following is an example: "actions": { "routerEvent": { "action": "router", - "abilityName": "com.example.entry.MainAbility", + "abilityName": "com.example.entry.EntryAbility", "params": { "message": "add detail" } diff --git a/en/application-dev/application-models/widget-development-stage.md b/en/application-dev/application-models/widget-development-stage.md deleted file mode 100644 index 3e542956072a31fbc8dbca097ae264dfe8ebfc5f..0000000000000000000000000000000000000000 --- a/en/application-dev/application-models/widget-development-stage.md +++ /dev/null @@ -1,599 +0,0 @@ -# FormExtensionAbility (Widget) - - -## Widget Overview - -FormExtensionAbility provides a service widget (also called widget), which is a set of UI components that display important information or operations specific to an application. It provides users with direct access to a desired application service, without the need to open the application first. - -A widget usually appears as a part of the UI of another application (which currently can only be a system application) and provides basic interactive features such as opening a UI page or sending a message. - -Before you get started, it would be helpful if you have a basic understanding of the following concepts: - -- Widget host: an application that displays the widget content and controls the widget location. - -- Widget Manager: a resident agent that provides widget management features such as periodic widget updates. - -- Widget provider: an atomic service that provides the widget content to display and controls how widget components are laid out and how they interact with users. - - -## Working Principles - -Figure 1 shows the working principles of the widget framework. - -**Figure 1** Widget framework working principles in the stage model -![form-extension](figures/form-extension.png) - -The widget host consists of the following modules: - -- Widget usage: provides operations such as creating, deleting, or updating a widget. - -- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It sends widget-related operations to the Widget Manager. - -The Widget Manager consists of the following modules: - -- Periodic updater: starts a scheduled task based on the update policy to periodically update a widget after it is added to the Widget Manager. - -- Cache manager: caches view information of a widget after it is added to the Widget Manager to directly return the cached data when the widget is obtained next time. This reduces the latency greatly. - -- Lifecycle manager: suspends update when a widget is switched to the background or is blocked, and updates and/or clears widget data during upgrade and deletion. - -- Object manager: manages RPC objects of the widget host. It is used to verify requests from the widget host and process callbacks after the widget update. - -- Communication adapter: communicates with the widget host and provider through RPCs. - -The widget provider consists of the following modules: - -- Widget service: implemented by the widget provider developer to process requests on widget creation, update, and deletion, and to provide corresponding widget services. - -- Instance manager: implemented by the widget provider developer for persistent management of widget instances allocated by the Widget Manager. - -- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It pushes update data to the Widget Manager. - -> **NOTE** -> -> You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager. - - -## Available APIs - -The **FormExtensionAbility** class has the following APIs. For details, see [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md). - -| API| Description| -| -------- | -------- | -| onAddForm(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a widget has been created.| -| onCastToNormalForm(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| -| onUpdateForm(formId: string): void | Called to notify the widget provider that a widget has been updated.| -| onChangeFormVisibility(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility.| -| onFormEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event.| -| onRemoveForm(formId: string): void| Called to notify the widget provider that a widget has been destroyed.| -| onConfigurationUpdate(config: Configuration): void | Called when the configuration of the environment where the widget is running is updated.| -| onShareForm?(formId: string): { [key: string]: any }| Called by the widget provider to receive shared widget data.| - -The **FormExtensionAbility** class also has a member context, that is, the FormExtensionContext class. For details, see [FormExtensionContext](../reference/apis/js-apis-inner-application-formExtensionContext.md). - -| API| Description| -| -------- | -------- | -| startAbility(want: Want, callback: AsyncCallback<void>): void | Starts UIAbility of the application to which a widget belongs. This API uses an asynchronous callback to return the result. (This is a system API and cannot be called by third-party applications. You must apply for the permission to use the API.)| -| startAbility(want: Want): Promise<void> | Starts UIAbility of the application to which a widget belongs. This API uses a promise to return the result. (This is a system API and cannot be called by third-party applications. You must apply for the permission to use the API.)| - -The **FormProvider** class has the following APIs. For details, see [FormProvider](../reference/apis/js-apis-app-form-formProvider.md). - -| API| Description| -| -------- | -------- | -| setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void; | Sets the next refresh time for a widget. This API uses an asynchronous callback to return the result.| -| setFormNextRefreshTime(formId: string, minute: number): Promise<void>; | Sets the next refresh time for a widget. This API uses a promise to return the result.| -| updateForm(formId: string, formBindingData: FormBindingData, callback: AsyncCallback<void>): void; | Updates a widget. This API uses an asynchronous callback to return the result.| -| updateForm(formId: string, formBindingData: FormBindingData): Promise<void>;| Updates a widget. This API uses a promise to return the result.| - -The **FormBindingData** class has the following APIs. For details, see [FormBindingData](../reference/apis/js-apis-app-form-formBindingData.md). - -| API| Description| -| -------- | -------- | -| createFormBindingData(obj?: Object \ string): FormBindingData| | Creates a **FormBindingData** object.| - - -## How to Develop - -The widget provider development based on the [stage model](stage-model-development-overview.md) involves the following key steps: - -- [Creating a FormExtensionAbility Instance](#creating-a-formextensionability-instance): Develop the lifecycle callback functions of FormExtensionAbility. - -- [Configuring the Widget Configuration File](#configuring-the-widget-configuration-file): Configure the application configuration file **module.json5** and profile configuration file. - -- [Persistently Storing Widget Data](#persistently-storing-widget-data): Perform persistent management on widget information. - -- [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed on a widget. - -- [Developing the Widget UI Page](#developing-the-widget-ui-page): Use HML+CSS+JSON to develop a JS widget UI page. - -- [Developing Widget Events](#developing-widget-events): Add the router and message events for a widget. - - -### Creating a FormExtensionAbility Instance - -To create a widget in the stage model, implement the lifecycle callbacks of **FormExtensionAbility**. Generate a widget template by referring to [Developing a Service Widget](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-development-service-widget-0000001263280425). - -1. Import related modules to **EntryFormAbility.ts**. - - ```ts - import FormExtension from '@ohos.app.form.FormExtensionAbility'; - import formBindingData from '@ohos.app.form.formBindingData'; - import formInfo from '@ohos.app.form.formInfo'; - import formProvider from '@ohos.app.form.formProvider'; - import dataStorage from '@ohos.data.storage'; - ``` - -2. Implement the FormExtension lifecycle callbacks in **EntryFormAbility.ts**. - - ```ts - export default class EntryFormAbility extends FormExtension { - onAddForm(want) { - console.info('[EntryFormAbility] onAddForm'); - // Called when the widget is created. The widget provider should return the widget data binding class. - let obj = { - "title": "titleOnCreate", - "detail": "detailOnCreate" - }; - let formData = formBindingData.createFormBindingData(obj); - return formData; - } - onCastToNormalForm(formId) { - // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. - console.info('[EntryFormAbility] onCastToNormalForm'); - } - onUpdateForm(formId) { - // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. - console.info('[EntryFormAbility] onUpdateForm'); - let obj = { - "title": "titleOnUpdate", - "detail": "detailOnUpdate" - }; - let formData = formBindingData.createFormBindingData(obj); - formProvider.updateForm(formId, formData).catch((error) => { - console.info('[EntryFormAbility] updateForm, error:' + JSON.stringify(error)); - }); - } - onChangeFormVisibility(newStatus) { - // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification. This callback takes effect only for system applications. - console.info('[EntryFormAbility] onChangeFormVisibility'); - } - onFormEvent(formId, message) { - // If the widget supports event triggering, override this method and implement the trigger. - console.info('[EntryFormAbility] onFormEvent'); - } - onRemoveForm(formId) { - // Delete widget data. - console.info('[EntryFormAbility] onRemoveForm'); - } - onConfigurationUpdate(config) { - console.info('[EntryFormAbility] nConfigurationUpdate, config:' + JSON.stringify(config)); - } - onAcquireFormState(want) { - return formInfo.FormState.READY; - } - } - ``` - -> **NOTE** -> -> FormExtensionAbility cannot reside in the background. Therefore, continuous tasks cannot be processed in the widget lifecycle callbacks. - -### Configuring the Widget Configuration File - -1. Configure ExtensionAbility information under **extensionAbilities** in the [module.json5 file](../quick-start/module-configuration-file.md). For a FormExtensionAbility, you must specify **metadata**. Specifically, set **name** to **ohos.extension.form** (fixed), and set **resource** to the index of the widget configuration information. - Example configuration: - - - ```json - { - "module": { - // ... - "extensionAbilities": [ - { - "name": "EntryFormAbility", - "srcEntrance": "./ets/entryformability/EntryFormAbility.ts", - "label": "$string:EntryFormAbility_label", - "description": "$string:EntryFormAbility_desc", - "type": "form", - "metadata": [ - { - "name": "ohos.extension.form", - "resource": "$profile:form_config" - } - ] - } - ] - } - } - ``` - -2. Configure the widget configuration information. In the **metadata** configuration item of FormExtensionAbility, you can specify the resource index of specific configuration information of the widget. For example, if resource is set to **$profile:form_config**, **form_config.json** in the **resources/base/profile/** directory of the development view is used as the profile configuration file of the widget. The following table describes the internal field structure. - **Table 1** Widget profile configuration file - - | Field| Description| Data Type| Initial Value Allowed| - | -------- | -------- | -------- | -------- | - | name | Class name of a widget. The value is a string with a maximum of 127 bytes.| String| No| - | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| - | src | Full path of the UI code corresponding to the widget.| String| No| - | window | Window-related configurations.| Object| Yes| - | isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean| No| - | colorMode | Color mode of the widget.
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String| Yes (initial value: **auto**)| - | supportDimensions | Grid styles supported by the widget.
**1 * 2**: indicates a grid with one row and two columns.
**2 * 2**: indicates a grid with two rows and two columns.
**2 * 4**: indicates a grid with two rows and four columns.
**4 * 4**: indicates a grid with four rows and four columns.| String array| No| - | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String| No| - | updateEnabled | Whether the widget can be updated periodically.
**true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**.
**false**: The widget cannot be updated periodically.| Boolean| No| - | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| String| Yes (initial value: **0:0**)| - | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer *N*, the interval is calculated by multiplying *N* and 30 minutes.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number| Yes (initial value: **0**)| - | formConfigAbility | Link to a specific page of the application. The value is a URI.| String| Yes (initial value: left empty)| - | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification.| String| Yes (initial value: left empty)| - | metaData | Metadata of the widget. This field contains the array of the **customizeData** field.| Object| Yes (initial value: left empty)| - - Example configuration: - - ```json - { - "forms": [ - { - "name": "widget", - "description": "This is a widget.", - "src": "./js/widget/pages/index/index", - "window": { - "designWidth": 720, - "autoDesignWidth": true - }, - "colorMode": "auto", - "isDefault": true, - "updateEnabled": true, - "scheduledUpdateTime": "10:30", - "updateDuration": 1, - "defaultDimension": "2*2", - "supportDimensions": [ - "2*2" - ] - } - ] - } - ``` - - -### Persistently Storing Widget Data - -A widget provider is usually started when it is needed to provide information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget. - - -```ts -const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store"; -async function storeFormInfo(formId: string, formName: string, tempFlag: boolean) { - // Only the widget ID (formId), widget name (formName), and whether the widget is a temporary one (tempFlag) are persistently stored. - let formInfo = { - "formName": formName, - "tempFlag": tempFlag, - "updateCount": 0 - }; - try { - const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); - // Put the widget information. - await storage.put(formId, JSON.stringify(formInfo)); - console.info(`[EntryFormAbility] storeFormInfo, put form info successfully, formId: ${formId}`); - await storage.flush(); - } catch (err) { - console.error(`[EntryFormAbility] failed to storeFormInfo, err: ${JSON.stringify(err)}`); - } -} - -export default class EntryFormAbility extends FormExtension { - // ... - onAddForm(want) { - console.info('[EntryFormAbility] onAddForm'); - - let formId = want.parameters["ohos.extra.param.key.form_identity"]; - let formName = want.parameters["ohos.extra.param.key.form_name"]; - let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; - // Persistently store widget data for subsequent use, such as instance acquisition and update. - // Implement this API based on project requirements. - storeFormInfo(formId, formName, tempFlag); - - let obj = { - "title": "titleOnCreate", - "detail": "detailOnCreate" - }; - let formData = formBindingData.createFormBindingData(obj); - return formData; - } -} -``` - -You should override **onRemoveForm** to implement widget data deletion. - - -```ts -const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store"; -async function deleteFormInfo(formId: string) { - try { - const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); - // Delete the widget information. - await storage.delete(formId); - console.info(`[EntryFormAbility] deleteFormInfo, del form info successfully, formId: ${formId}`); - await storage.flush(); - } catch (err) { - console.error(`[EntryFormAbility] failed to deleteFormInfo, err: ${JSON.stringify(err)}`); - } -} - -// ... - -export default class EntryFormAbility extends FormExtension { - // ... - onRemoveForm(formId) { - console.info('[EntryFormAbility] onRemoveForm'); - // Delete the persistent widget instance data. - // Implement this API based on project requirements. - deleteFormInfo(formId); - } -} -``` - -For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). - -The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. - -- Normal widget: a widget persistently used by the widget host - -- Temporary widget: a widget temporarily used by the widget host - -Data of a temporary widget will be deleted on the Widget Manager if the widget framework is killed and restarted. The widget provider, however, is not notified of the deletion and still keeps the data. Therefore, the widget provider needs to clear the data of temporary widgets proactively if the data has been kept for a long period of time. If the widget host has converted a temporary widget into a normal one, the widget provider should change the widget data from temporary storage to persistent storage. Otherwise, the widget data may be deleted by mistake. - - -### Updating Widget Data - -When an application initiates a scheduled or periodic update, the application obtains the latest data and calls **updateForm()** to update the widget. - - -```ts -onUpdateForm(formId) { - // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. - console.info('[EntryFormAbility] onUpdateForm'); - let obj = { - "title": "titleOnUpdate", - "detail": "detailOnUpdate" - }; - let formData = formBindingData.createFormBindingData(obj); - // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged. - formProvider.updateForm(formId, formData).catch((error) => { - console.info('[EntryFormAbility] updateForm, error:' + JSON.stringify(error)); - }); -} -``` - - -### Developing the Widget UI Page - -You can use the web-like paradigm (HML+CSS+JSON) to develop JS widget pages. This section describes how to develop a page shown below. - -![widget-development-stage](figures/widget-development-stage.png) - -> **NOTE** -> -> Only the JavaScript-based web-like development paradigm is supported when developing the widget UI. - -- HML: uses web-like paradigm components to describe the widget page information. - - ```html -
- -
- -
-
- {{title}} - {{detail}} -
-
-
- ``` - -- CSS: defines style information about the web-like paradigm components in HML. - - ```css - .container { - flex-direction: column; - justify-content: center; - align-items: center; - } - - .bg-img { - flex-shrink: 0; - height: 100%; - } - - .container-inner { - flex-direction: column; - justify-content: flex-end; - align-items: flex-start; - height: 100%; - width: 100%; - padding: 12px; - } - - .title { - font-size: 19px; - font-weight: bold; - color: white; - text-overflow: ellipsis; - max-lines: 1; - } - - .detail_text { - font-size: 16px; - color: white; - opacity: 0.66; - text-overflow: ellipsis; - max-lines: 1; - margin-top: 6px; - } - ``` - -- JSON: defines data and event interaction on the widget UI page. - - ```json - { - "data": { - "title": "TitleDefault", - "detail": "TextDefault" - }, - "actions": { - "routerEvent": { - "action": "router", - "abilityName": "EntryAbility", - "params": { - "message": "add detail" - } - } - } - } - ``` - - -### Developing Widget Events - -You can set router and message events for components on a widget. The router event applies to ability redirection, and the message event applies to custom click events. - -The key steps are as follows: - -1. Set the **onclick** field in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. - -2. Set the router event. - - **action**: **"router"**, which indicates a router event. - - **abilityName**: name of the ability to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name of the stage model created by DevEco Studio is EntryAbility. - - **params**: custom parameters passed to the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the main ability in the stage model, you can obtain **want** and its **parameters** field. - -3. Set the message event. - - **action**: **"message"**, which indicates a message event. - - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onFormEvent()**. - -The following is an example: - -- HML file: - - ```html -
- -
- -
-
- {{title}} - {{detail}} -
-
-
- ``` - -- CSS file: - - ```css - .container { - flex-direction: column; - justify-content: center; - align-items: center; - } - - .bg-img { - flex-shrink: 0; - height: 100%; - } - - .container-inner { - flex-direction: column; - justify-content: flex-end; - align-items: flex-start; - height: 100%; - width: 100%; - padding: 12px; - } - - .title { - font-size: 19px; - font-weight: bold; - color: white; - text-overflow: ellipsis; - max-lines: 1; - } - - .detail_text { - font-size: 16px; - color: white; - opacity: 0.66; - text-overflow: ellipsis; - max-lines: 1; - margin-top: 6px; - } - ``` - -- JSON file: - - ```json - { - "data": { - "title": "TitleDefault", - "detail": "TextDefault" - }, - "actions": { - "routerEvent": { - "action": "router", - "abilityName": "EntryAbility", - "params": { - "info": "router info", - "message": "router message" - } - }, - "messageEvent": { - "action": "message", - "params": { - "detail": "message detail" - } - } - } - } - ``` - -- Receive the router event and obtain parameters in UIAbility. - - ```ts - import UIAbility from '@ohos.app.ability.UIAbility' - - export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - // Obtain the info parameter passed in the router event. - if (want.parameters.info === "router info") { - // Do something. - // console.log("router info:" + want.parameters.info) - } - // Obtain the message parameter passed in the router event. - if (want.parameters.message === "router message") { - // Do something. - // console.log("router message:" + want.parameters.message) - } - } - // ... - }; - ``` - -- Receive the message event in FormExtensionAbility and obtain parameters. - - ```ts - import FormExtension from '@ohos.app.form.FormExtensionAbility'; - - export default class FormAbility extends FormExtension { - // ... - onFormEvent(formId, message) { - // Obtain the detail parameter passed in the message event. - let msg = JSON.parse(message) - if (msg.params.detail === "message detail") { - // Do something. - // console.log("message info:" + msg.params.detail) - } - } - // ... - }; - ``` - diff --git a/en/application-dev/application-models/widget-switch.md b/en/application-dev/application-models/widget-switch.md index 0de83a6593f521e3b51b84dea5ff275e7ee5450f..2f8a0a41b2e1b20824a19d08c98f67e39cd05df6 100644 --- a/en/application-dev/application-models/widget-switch.md +++ b/en/application-dev/application-models/widget-switch.md @@ -11,7 +11,7 @@ Widget switching involves the following parts: | Configuration Item | FA Model | Stage Model | | ---------------- | ------------------------------------------- | ------------------------------------------------------------ | | Configuration item location | **formAbility** and **forms** are in the **config.json** file.| **extensionAbilities** (configuration for **formExtensionAbility**) is in the **module.json5** file in the level-1 directory, and **forms** (configuration for **forms** contained in **formExtensionAbility**) is in the **form_config.json** file in the level-2 directory.| -| Widget code path | Specified by **srcPath**, without the file name. | Specified by **srcEnty**, with the file name. | +| Widget code path | Specified by **srcPath**, without the file name. | Specified by **srcEntry**, with the file name. | | Programming language | **srcLanguage** can be set to **js** or **ets**. | This configuration item is unavailable. Only ets is supported. | | Whether to enable widgets | formsEnabled | This configuration item is unavailable. The setting of **type** set to **form** means that the widgets are enabled. | | Ability type | type: service | type: form | @@ -32,7 +32,7 @@ Figure 2 Widget configuration differences | Item| FA Model| Stage Model| | -------- | -------- | -------- | -| Entry file| **form.ts** in the directory pointed to by **srcPath**| File pointed to by **srcEnty**| +| Entry file| **form.ts** in the directory pointed to by **srcPath**| File pointed to by **srcEntry**| | Lifecycle| export default| import FormExtension from '\@ohos.app.form.FormExtensionAbility';
export default class FormAbility extends FormExtension| diff --git a/en/application-dev/application-models/windowextensionability.md b/en/application-dev/application-models/windowextensionability.md index a307a1da5e1c21e11b71d054b8300bb35ddf0522..975b350a47966341bd9c60046f9b69ee011f9ae3 100644 --- a/en/application-dev/application-models/windowextensionability.md +++ b/en/application-dev/application-models/windowextensionability.md @@ -43,7 +43,7 @@ To implement an embedded application, manually create a WindowExtensionAbility i onWindowReady(window) { window.loadContent('WindowExtAbility/pages/index1').then(() => { window.getProperties().then((pro) => { - console.log("WindowExtension " + JSON.stringify(pro)); + console.info("WindowExtension " + JSON.stringify(pro)); }) window.show(); }) @@ -59,7 +59,7 @@ To implement an embedded application, manually create a WindowExtensionAbility i } ``` -4. Register the WindowExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the **Module** project. Set **type** to **"window"** and **srcEnty** to the code path of the ExtensionAbility component. +4. Register the WindowExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the **Module** project. Set **type** to **"window"** and **srcEntry** to the code path of the ExtensionAbility component. ```json { @@ -67,7 +67,7 @@ To implement an embedded application, manually create a WindowExtensionAbility i "extensionAbilities": [ { "name": "WindowExtAbility", - "srcEnty": "./ets/WindowExtAbility/WindowExtAbility.ts", + "srcEntry": "./ets/WindowExtAbility/WindowExtAbility.ts", "icon": "$media:icon", "description": "WindowExtension", "type": "window",