diff --git a/en/application-dev/ability-deprecated/ability-delegator.md b/en/application-dev/ability-deprecated/ability-delegator.md index b32d472176a5b6270fece94ae4bd8ae9a7bd73fa..f72a192dc510c28104511fb1530a915c9f9827cc 100644 --- a/en/application-dev/ability-deprecated/ability-delegator.md +++ b/en/application-dev/ability-deprecated/ability-delegator.md @@ -63,7 +63,7 @@ For details about how to use DevEco Studio to start the test framework, see [Ope **Example** ```javascript -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); @@ -87,11 +87,11 @@ abilityDelegator.addAbilityMonitor(monitor).then(() => { **Modules to Import** ```javascript -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; ``` ```javascript -var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() +var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); ``` ### Starting an Ability and Listening for the Ability State diff --git a/en/application-dev/ability-deprecated/context-userguide.md b/en/application-dev/ability-deprecated/context-userguide.md index ac65d92cb9422d040ff16cab1640cd1f9bed5d5c..1340e72918e141dd3b95b5ddc8dbc11258f83493 100644 --- a/en/application-dev/ability-deprecated/context-userguide.md +++ b/en/application-dev/ability-deprecated/context-userguide.md @@ -4,11 +4,11 @@ **Context** provides the capability of obtaining contextual information of an application. - The OpenHarmony application framework has two models: Feature Ability (FA) model and stage model. Correspondingly, there are two sets of context mechanisms. **application/BaseContext** is a common context base class. It uses the **stageMode** attribute to specify whether the context is used for the stage model. +The OpenHarmony application framework has two models: Feature Ability (FA) model and stage model. Correspondingly, there are two sets of context mechanisms. **application/BaseContext** is a common context base class. It uses the **stageMode** attribute to specify whether the context is used for the stage model. -- FA model +- FA model -Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance. + Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance. - Stage model @@ -54,6 +54,7 @@ setDisplayOrientation(orientation: bundle.DisplayOrientation): Promise; The methods are used to set the display orientation of the current ability. **Example** + ```javascript import featureAbility from '@ohos.ability.featureAbility' import bundle from '@ohos.bundle'; @@ -96,13 +97,13 @@ Obtain the context by calling **context.getApplicationContext()** in **Ability** **Example** ```javascript -import Ability from "@ohos.application.Ability"; +import UIAbility from '@ohos.app.ability.UIAbility'; var lifecycleid; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate() { - console.log("MainAbility onCreate") + console.log("EntryAbility onCreate") let AbilityLifecycleCallback = { onAbilityCreate(ability){ console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); @@ -191,25 +192,25 @@ Obtain the context from the **context** attribute in **Ability**. **Example** ```javascript -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] MainAbility onCreate") + console.log("[Demo] EntryAbility onCreate") globalThis.abilityWant = want; } onDestroy() { - console.log("[Demo] MainAbility onDestroy") + console.log("[Demo] EntryAbility onDestroy") } onWindowStageCreate(windowStage) { // Set the main page for this ability when the main window is created. - console.log("[Demo] MainAbility onWindowStageCreate") + console.log("[Demo] EntryAbility onWindowStageCreate") // Obtain AbilityContext and print the ability information. let context = this.context; - console.log("[Demo] MainAbility bundleName " + context.abilityInfo.bundleName) + console.log("[Demo] EntryAbility bundleName " + context.abilityInfo.bundleName) windowStage.loadContent("pages/index", (err, data) => { if (err.code) { @@ -222,17 +223,17 @@ export default class MainAbility extends Ability { onWindowStageDestroy() { // Release the UI related resources when the main window is destroyed. - console.log("[Demo] MainAbility onWindowStageDestroy") + console.log("[Demo] EntryAbility onWindowStageDestroy") } onForeground() { // The ability is switched to run in the foreground. - console.log("[Demo] MainAbility onForeground") + console.log("[Demo] EntryAbility onForeground") } onBackground() { // The ability is switched to run in the background. - console.log("[Demo] MainAbility onBackground") + console.log("[Demo] EntryAbility onBackground") } }; ``` @@ -256,16 +257,16 @@ Use the API described in the table below to obtain the context associated with a **Example** ```ts -// MainAbility.ts -import Ability from '@ohos.application.Ability' +// EntryAbility.ts +import UIAbility from '@ohos.app.ability.UIAbility'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] MainAbility onCreate") + console.log("[Demo] EntryAbility onCreate") } onDestroy() { - console.log("[Demo] MainAbility onDestroy") + console.log("[Demo] EntryAbility onDestroy") } onWindowStageCreate(windowStage) { @@ -283,7 +284,7 @@ export default class MainAbility extends Ability { ```ts // pages/index.ets -import context from '@ohos.application.context' +import context from '@ohos.app.ability.context' type Context = context.Context diff --git a/en/application-dev/ability-deprecated/continuationmanager.md b/en/application-dev/ability-deprecated/continuationmanager.md index 0ba79f95acf165d604d8f854832703d7fc4af3f8..12db9781c5a5f6548be98f27a426e8a3be354ae9 100644 --- a/en/application-dev/ability-deprecated/continuationmanager.md +++ b/en/application-dev/ability-deprecated/continuationmanager.md @@ -126,7 +126,7 @@ As the entry of the ability continuation capability, **continuationManager** is if (needGrantPermission) { try { // globalThis.context is Ability.context, which must be assigned a value in the MainAbility.ts file in advance. - await globalThis.context.requestPermissionsFromUser(permissions); + await atManger.requestPermissionsFromUser(globalThis.context, permissions); } catch (err) { console.error('app permission request permissions error' + JSON.stringify(err)); } @@ -175,7 +175,7 @@ As the entry of the ability continuation capability, **continuationManager** is let want = { deviceId: remoteDeviceId, bundleName: 'ohos.samples.continuationmanager', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' }; globalThis.abilityContext.startAbility(want).then((data) => { console.info('StartRemoteAbility finished, ' + JSON.stringify(data)); diff --git a/en/application-dev/ability-deprecated/fa-brief.md b/en/application-dev/ability-deprecated/fa-brief.md index 5ad79cfe259f1fb9cf865b9d6f496c0f31c47ae0..4bdbfa4d7f3c96663cad5e90b9cd0d187a1e8709 100644 --- a/en/application-dev/ability-deprecated/fa-brief.md +++ b/en/application-dev/ability-deprecated/fa-brief.md @@ -40,4 +40,4 @@ For details about the project directory structure of the FA model, see [OpenHarm For details about how to configure the application package structure of the FA model, see [Application Package Structure Configuration File](../quick-start/application-configuration-file-overview-fa.md). - \ No newline at end of file + diff --git a/en/application-dev/ability-deprecated/fa-formability.md b/en/application-dev/ability-deprecated/fa-formability.md index a91ca4b9baf98f32bad7ea081024d74949baf726..5c08a1b0b3955472d6f3b16cf7a343a083a0116a 100644 --- a/en/application-dev/ability-deprecated/fa-formability.md +++ b/en/application-dev/ability-deprecated/fa-formability.md @@ -63,9 +63,9 @@ To create an FA widget, you need to implement lifecycle callbacks using the **Li 1. Import the required modules. ```javascript - import formBindingData from '@ohos.application.formBindingData' - import formInfo from '@ohos.application.formInfo' - import formProvider from '@ohos.application.formProvider' + import formBindingData from '@ohos.app.form.formBindingData'; + import formInfo from '@ohos.app.form.formInfo'; + import formProvider from '@ohos.app.form.formProvider'; ``` 2. Implement lifecycle callbacks for the widget. @@ -158,7 +158,7 @@ The widget configuration file is named **config.json**. Find the **config.json** | 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**) | + | 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) | | jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. | String | No | @@ -206,7 +206,7 @@ A widget provider is usually started when it is needed to provide information ab 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 information for subsequent use, such as widget instance retrieval or update. + // Persistently store widget data for subsequent use, such as widget instance retrieval or update. // The storeFormInfo API is not implemented here. storeFormInfo(formId, formName, tempFlag, want); @@ -231,9 +231,9 @@ You should override **onDestroy** to implement widget data deletion. } ``` -For details about how to implement persistence data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). +For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). -The **Want** passed by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. +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 @@ -254,14 +254,14 @@ onUpdate(formId) { "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. + // 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.log('FormAbility updateForm, error:' + JSON.stringify(error)); }); } ``` -### Developing Widget UI Pages +### Developing the Widget UI Page You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. @@ -335,7 +335,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme "actions": { "routerEvent": { "action": "router", - "abilityName": "com.example.entry.MainAbility", + "abilityName": "com.example.entry.EntryAbility", "params": { "message": "add detail" } @@ -353,12 +353,12 @@ Now you've got a widget shown below. 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. For the router event, set the following attributes: - - **action**: **router**, which indicates a router event. - - **abilityName**: target ability name, for example, **com.example.entry.MainAbility**, which is the default main ability name in DevEco Studio for the FA model. - - **params**: custom parameters of the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the main ability in the FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field. -3. For the message event, set the following attributes: - - **action**: **message**, which indicates a message event. +2. Set the router event. + - **action**: **"router"**, which indicates a router event. + - **abilityName**: target ability name, for example, **com.example.entry.EntryAbility**, which is the default UIAbility name in DevEco Studio for the FA model. + - **params**: custom parameters of 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. - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onEvent**. The code snippet is as follows: @@ -388,7 +388,7 @@ The code snippet is as follows: "actions": { "routerEvent": { "action": "router", - "abilityName": "com.example.entry.MainAbility", + "abilityName": "com.example.entry.EntryAbility", "params": { "message": "add detail" } @@ -401,4 +401,4 @@ The code snippet is as follows: } } } - ``` \ No newline at end of file + ``` diff --git a/en/application-dev/ability-deprecated/fa-pageability.md b/en/application-dev/ability-deprecated/fa-pageability.md index 2f4741b80ef771c9b478d32a7713b597fb65c2d4..28b5ce36e292acc9e350f8ae96cb7bcf17f8c8c3 100644 --- a/en/application-dev/ability-deprecated/fa-pageability.md +++ b/en/application-dev/ability-deprecated/fa-pageability.md @@ -135,13 +135,13 @@ Obtain **deviceId** from **DeviceManager**. The sample code is as follows: if (typeof dmClass === 'object' && dmClass != null) { let list = dmClass.getTrustedDeviceListSync(); if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null"); + console.log("EntryAbility onButtonClick getRemoteDeviceId err: list is null"); return; } - console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); + console.log("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); return list[0].deviceId; } else { - console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); + console.log("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null"); } } ``` diff --git a/en/application-dev/ability-deprecated/fa-serviceability.md b/en/application-dev/ability-deprecated/fa-serviceability.md index cf766f35f72c76eb738d3b168d39cbcba0f21da3..0c2a65aebf1076e739009101980633e41f77e8a7 100644 --- a/en/application-dev/ability-deprecated/fa-serviceability.md +++ b/en/application-dev/ability-deprecated/fa-serviceability.md @@ -24,8 +24,6 @@ The differences between **onCommand()** and **onConnect()** are as follows: 1. Override the Service ability-related lifecycle callbacks to implement your own logic for processing interaction requests. - - ```ts export default { onStart() { @@ -47,7 +45,7 @@ The differences between **onCommand()** and **onConnect()** are as follows: } } ``` - + 2. Register a Service ability. Declare the Service ability in the **config.json** file by setting its **type** attribute to **service**. @@ -155,7 +153,7 @@ You can use either of the following methods to connect to a Service ability: ```ts import prompt from '@system.prompt' - + var option = { onConnect: function onConnectCallback(element, proxy) { console.log(`onConnectLocalService onConnectDone`); @@ -194,7 +192,7 @@ You can use either of the following methods to connect to a Service ability: ```ts import featureAbility from '@ohos.ability.featureAbility' - + let want = { bundleName: "com.jstest.service", abilityName: "com.jstest.service.ServiceAbility" @@ -208,7 +206,7 @@ You can use either of the following methods to connect to a Service ability: ```ts import rpc from "@ohos.rpc" - + class ServiceAbilityStub extends rpc.RemoteObject { constructor(des: any) { if (typeof des === 'string') { @@ -218,7 +216,7 @@ You can use either of the following methods to connect to a Service ability: return; } } - + onRemoteRequest(code: number, data: any, reply: any, option: any) { console.log("onRemoteRequest called"); // Execute the service logic. @@ -235,7 +233,7 @@ You can use either of the following methods to connect to a Service ability: return true; } } - + export default { onStart() { console.log('ServiceAbility onStart'); diff --git a/en/application-dev/ability-deprecated/stage-ability-continuation.md b/en/application-dev/ability-deprecated/stage-ability-continuation.md index 7a11716f18f2c8b866e1fd11722ae0e07a32d4ce..b53d57d849c8c771b92d4e86a2095163aab0a395 100644 --- a/en/application-dev/ability-deprecated/stage-ability-continuation.md +++ b/en/application-dev/ability-deprecated/stage-ability-continuation.md @@ -127,7 +127,7 @@ The code snippets provided below are all from [Sample](https://gitee.com/openhar if (needGrantPermission) { Logger.info("app permission needGrantPermission") try { - await this.context.requestPermissionsFromUser(permissions) + await accessManger.requestPermissionsFromUser(this.context, permissions) } catch (err) { Logger.error(`app permission ${JSON.stringify(err)}`) } @@ -147,8 +147,8 @@ The code snippets provided below are all from [Sample](https://gitee.com/openhar Modules to import: ```javascript - import Ability from '@ohos.application.Ability'; - import AbilityConstant from '@ohos.application.AbilityConstant'; + import UIAbility from '@ohos.app.ability.UIAbility'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; ``` To implement ability continuation, you must implement this API and have the value **AGREE** returned. @@ -185,14 +185,14 @@ The code snippets provided below are all from [Sample](https://gitee.com/openhar Example ```javascript - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; import distributedObject from '@ohos.data.distributedDataObject'; - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { storage : LocalStorag; onCreate(want, launchParam) { - Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) + Logger.info(`EntryAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { // Obtain the user data from the want parameter. let workInput = want.parameters.work @@ -207,8 +207,6 @@ The code snippets provided below are all from [Sample](https://gitee.com/openhar ``` For a singleton ability, use **onNewWant()** to achieve the same implementation. - - ### Data Continuation Use distributed objects. @@ -220,12 +218,12 @@ In the ability continuation scenario, the distributed data object is used to syn - In **onContinue()**, the initiator saves the data to be migrated to the distributed object, calls the **save()** API to save the data and synchronize the data to the target device, sets the session ID, and sends the session ID to the target device through **wantParam**. ```javascript - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; import distributedObject from '@ohos.data.distributedDataObject'; var g_object = distributedObject.createDistributedObject({data:undefined}); - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { sessionId : string; onContinue(wantParam : {[key: string]: any}) { @@ -256,34 +254,33 @@ In the ability continuation scenario, the distributed data object is used to syn - The target device obtains the session ID from **onCreate()**, creates a distributed object, and associates the distributed object with the session ID. In this way, the distributed object can be synchronized. Before calling **restoreWindowStage**, ensure that all distributed objects required for continuation have been associated. ```javascript - import Ability from '@ohos.application.Ability'; - import distributedObject from '@ohos.data.distributedDataObject'; + import UIAbility from '@ohos.app.ability.UIAbility'; + import distributedObject from '@ohos.data.distributedDataObject'; - var g_object = distributedObject.createDistributedObject({data:undefined}); + var g_object = distributedObject.createDistributedObject({data:undefined}); - export default class MainAbility extends Ability { - storage : LocalStorag; + export default class EntryAbility extends UIAbility { + storage : LocalStorag; + onCreate(want, launchParam) { + Logger.info(`EntryAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) + if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { + // Obtain the session ID of the distributed data object from the want parameter. + this.sessionId = want.parameters.session + Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`) - onCreate(want, launchParam) { - Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) - if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { - // Obtain the session ID of the distributed data object from the want parameter. - this.sessionId = want.parameters.session - Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`) + // Before fetching data from the remote device, reset g_object.data to undefined. + g_object.data = undefined; + // Set the session ID, so the target will fetch data from the remote device. + g_object.setSessionId(this.sessionId); - // Before fetching data from the remote device, reset g_object.data to undefined. - g_object.data = undefined; - // Set the session ID, so the target will fetch data from the remote device. - g_object.setSessionId(this.sessionId); + AppStorage.SetOrCreate('ContinueStudy', g_object.data) + this.storage = new LocalStorage(); + this.context.restoreWindowStage(this.storage); + } - AppStorage.SetOrCreate('ContinueStudy', g_object.data) - this.storage = new LocalStorage(); - this.context.restoreWindowStage(this.storage); - } - - } - } + } + } ``` @@ -309,5 +306,3 @@ In the ability continuation scenario, the distributed data object is used to syn ### Best Practice For better user experience, you are advised to use the **wantParam** parameter to transmit data smaller than 100 KB and use distributed objects to transmit data larger than 100 KB. - - \ No newline at end of file diff --git a/en/application-dev/ability-deprecated/stage-ability.md b/en/application-dev/ability-deprecated/stage-ability.md index 97ba5cff5cc083563f1d0f78c7b499bff2cd2050..60f954c78f306193e7bfefe1e6ceee2babf86da4 100644 --- a/en/application-dev/ability-deprecated/stage-ability.md +++ b/en/application-dev/ability-deprecated/stage-ability.md @@ -56,8 +56,8 @@ The table below describes the APIs provided by the **Ability** class. For detail ### Implementing AbilityStage and Ability Lifecycle Callbacks To create Page abilities for an application in the stage model, you must implement the **AbilityStage** class and ability lifecycle callbacks, and use the **Window** class to set the pages. The sample code is as follows: 1. Import the **AbilityStage** module. - ``` - import AbilityStage from "@ohos.application.AbilityStage" + ```ts + import AbilityStage from "@ohos.app.ability.AbilityStage"; ``` 2. Implement the **AbilityStage** class. The default relative path generated by the APIs is **entry\src\main\ets\Application\AbilityStage.ts**. ```ts @@ -69,41 +69,41 @@ To create Page abilities for an application in the stage model, you must impleme ``` 3. Import the **Ability** module. ```js - import Ability from '@ohos.application.Ability' + import UIAbility from '@ohos.app.ability.UIAbility'; ``` -4. Implement the lifecycle callbacks of the **Ability** class. The default relative path generated by the APIs is **entry\src\main\ets\MainAbility\MainAbility.ts**. +4. Implement the lifecycle callbacks of the **UIAbility** class. The default relative path generated by the APIs is **entry\src\main\ets\entryability\EntryAbility.ts**. In the **onWindowStageCreate(windowStage)** API, use **loadContent** to set the application page to be loaded. For details about how to use the **Window** APIs, see [Window Development](../windowmanager/application-window-stage.md). ```ts - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("MainAbility onCreate") + console.log("EntryAbility onCreate") } - + onDestroy() { - console.log("MainAbility onDestroy") + console.log("EntryAbility onDestroy") } - + onWindowStageCreate(windowStage) { - console.log("MainAbility onWindowStageCreate") - + console.log("EntryAbility onWindowStageCreate") + windowStage.loadContent("pages/index").then(() => { - console.log("MainAbility load content succeed") + console.log("EntryAbility load content succeed") }).catch((error) => { - console.error("MainAbility load content failed with error: " + JSON.stringify(error)) + console.error("EntryAbility load content failed with error: " + JSON.stringify(error)) }) } - + onWindowStageDestroy() { - console.log("MainAbility onWindowStageDestroy") + console.log("EntryAbility onWindowStageDestroy") } - + onForeground() { - console.log("MainAbility onForeground") + console.log("EntryAbility onForeground") } - + onBackground() { - console.log("MainAbility onBackground") + console.log("EntryAbility onBackground") } } ``` @@ -113,7 +113,8 @@ Both the **AbilityStage** and **Ability** classes have the **context** attribute The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the **context** attribute in the **AbilityStage** class. The sample code is as follows: ```ts -import AbilityStage from "@ohos.application.AbilityStage" +import AbilityStage from "@ohos.app.ability.AbilityStage"; + export default class MyAbilityStage extends AbilityStage { onCreate() { console.log("MyAbilityStage onCreate") @@ -132,52 +133,32 @@ export default class MyAbilityStage extends AbilityStage { The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the **context** attribute in the **Ability** class. The sample code is as follows: ```ts -import Ability from '@ohos.application.Ability' -export default class MainAbility extends Ability { +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("MainAbility onCreate") + console.log("EntryAbility onCreate") let context = this.context - console.log("MainAbility bundleCodeDir" + context.bundleCodeDir) + console.log("EntryAbility bundleCodeDir" + context.bundleCodeDir) let abilityInfo = this.context.abilityInfo; - console.log("MainAbility ability bundleName" + abilityInfo.bundleName) - console.log("MainAbility ability name" + abilityInfo.name) + console.log("EntryAbility ability bundleName" + abilityInfo.bundleName) + console.log("EntryAbility ability name" + abilityInfo.name) let config = this.context.config - console.log("MainAbility config language" + config.language) + console.log("EntryAbility config language" + config.language) } } ``` -### Requesting Permissions -If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the respective permission from consumers. During application development, you need to specify the involved sensitive permissions, declare the required permissions in **module.json5**, and use the **requestPermissionsFromUser** API to request the permission from consumers in the form of a dialog box. The following uses the permission for calendar access as an example. - -Declare the required permission in the **module.json5** file. -```json -"requestPermissions": [ - { - "name": "ohos.permission.READ_CALENDAR" - } -] -``` -Request the permission from consumers in the form of a dialog box: -```ts -let context = this.context -let permissions: Array = ['ohos.permission.READ_CALENDAR'] -context.requestPermissionsFromUser(permissions).then((data) => { - console.log("Succeed to request permission from user with data: " + JSON.stringify(data)) -}).catch((error) => { - console.log("Failed to request permission from user with error: " + JSON.stringify(error)) -}) -``` ### Notifying of Environment Changes -Environment changes include changes of global configurations and ability configurations. Currently, the global configurations include the system language and color mode. The change of global configurations is generally triggered by configuration items in **Settings** or icons in **Control Panel**. The ability configuration is specific to a single **Ability** instance, including the display ID, screen resolution, and screen orientation. The configuration is related to the display where the ability is located, and the change is generally triggered by the window. For details on the configuration, see [Configuration](../reference/apis/js-apis-configuration.md). +Environment changes include changes of global configurations and ability configurations. Currently, the global configurations include the system language and color mode. The change of global configurations is generally triggered by configuration items in **Settings** or icons in **Control Panel**. The ability configuration is specific to a single **Ability** instance, including the display ID, screen resolution, and screen orientation. The configuration is related to the display where the ability is located, and the change is generally triggered by the window. Before configuring a project, define the project in the [Configuration](../reference/apis/js-apis-application-configuration.md) class. -For an application in the stage model, when the configuration changes, its abilities are not restarted, but the **onConfigurationUpdated(config: Configuration)** callback is triggered. If the application needs to perform processing based on the change, you can overwrite **onConfigurationUpdated**. Note that the **Configuration** object in the callback contains all the configurations of the current ability, not only the changed configurations. +For an application in the stage model, when the configuration changes, its abilities are not restarted, but the **onConfigurationUpdated(config: Configuration)** callback is triggered. If the application needs to perform processing based on the change, you can override **onConfigurationUpdated**. Note that the **Configuration** object in the callback contains all the configurations of the current ability, not only the changed configurations. The following example shows the implementation of the **onConfigurationUpdated** callback in the **AbilityStage** class. The callback is triggered when the system language and color mode are changed. ```ts -import AbilityStage from '@ohos.application.AbilityStage' -import ConfigurationConstant from '@ohos.application.ConfigurationConstant' +import AbilityStage from '@ohos.app.ability.AbilityStage'; +import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; export default class MyAbilityStage extends AbilityStage { onConfigurationUpdated(config) { @@ -190,10 +171,10 @@ export default class MyAbilityStage extends AbilityStage { The following example shows the implementation of the **onConfigurationUpdated** callback in the **Ability** class. The callback is triggered when the system language, color mode, or display parameters (such as the direction and density) change. ```ts -import Ability from '@ohos.application.Ability' -import ConfigurationConstant from '@ohos.application.ConfigurationConstant' +import UIAbility from '@ohos.app.ability.UIAbility'; +import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { direction : number; onCreate(want, launchParam) { @@ -229,7 +210,7 @@ let context = this.context var want = { "deviceId": "", "bundleName": "com.example.MyApplication", - "abilityName": "MainAbility" + "abilityName": "EntryAbility" }; context.startAbility(want).then(() => { console.log("Succeed to start ability") @@ -246,7 +227,7 @@ let context = this.context var want = { "deviceId": getRemoteDeviceId(), "bundleName": "com.example.MyApplication", - "abilityName": "MainAbility" + "abilityName": "EntryAbility" }; context.startAbility(want).then(() => { console.log("Succeed to start remote ability") @@ -261,17 +242,17 @@ function getRemoteDeviceId() { if (typeof dmClass === 'object' && dmClass != null) { var list = dmClass.getTrustedDeviceListSync(); if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null"); + console.log("EntryAbility onButtonClick getRemoteDeviceId err: list is null"); return; } - console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); + console.log("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); return list[0].deviceId; } else { - console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); + console.log("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null"); } } ``` -Request the permission **ohos.permission.DISTRIBUTED_DATASYNC** from consumers. This permission is used for data synchronization. For details about the sample code for requesting the permission, see [Requesting Permissions](#requesting-permissions). +Request the permission **ohos.permission.DISTRIBUTED_DATASYNC** from consumers. This permission is used for data synchronization. For details about the sample code for requesting permissions, see [abilityAccessCtrl.requestPermissionsFromUse](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9). ### Starting an Ability with the Specified Page If the launch type of an ability is set to **singleton** and the ability has been started, the **onNewWant** callback is triggered when the ability is started again. You can pass start options through the **want**. For example, to start an ability with the specified page, use the **uri** or **parameters** parameter in the **want** to pass the page information. Currently, the ability in the stage model cannot directly use the **router** capability. You must pass the start options to the custom component and invoke the **router** method to display the specified page during the custom component lifecycle management. The sample code is as follows: @@ -281,7 +262,7 @@ async function reStartAbility() { try { await this.context.startAbility({ bundleName: "com.sample.MyApplication", - abilityName: "MainAbility", + abilityName: "EntryAbility", uri: "pages/second" }) console.log('start ability succeed') @@ -293,9 +274,9 @@ async function reStartAbility() { Obtain the **want** parameter that contains the page information from the **onNewWant** callback of the ability. ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onNewWant(want, launchParams) { globalThis.newWant = want } @@ -321,5 +302,3 @@ struct Index { } } ``` - - \ No newline at end of file diff --git a/en/application-dev/ability-deprecated/stage-brief.md b/en/application-dev/ability-deprecated/stage-brief.md index 2d5474e2c2f0e8328add287481b5ea47abcb2725..190644c2c0d7e114d0e898de1a8837695bdf049e 100644 --- a/en/application-dev/ability-deprecated/stage-brief.md +++ b/en/application-dev/ability-deprecated/stage-brief.md @@ -111,4 +111,4 @@ For details about the project directory structure of the stage model, see [OpenH For details about how to configure the application package structure of the stage model, see [Application Package Structure Configuration File](../quick-start/application-configuration-file-overview-stage.md). - \ No newline at end of file + diff --git a/en/application-dev/ability-deprecated/stage-call.md b/en/application-dev/ability-deprecated/stage-call.md index e447dc4fd89f99948ebb379de7010c4db9486488..71f5f6934dda385161f4adcb95837924c691c278 100644 --- a/en/application-dev/ability-deprecated/stage-call.md +++ b/en/application-dev/ability-deprecated/stage-call.md @@ -24,8 +24,10 @@ The ability call process is as follows: - The callee ability, which holds a **Callee** object, uses **on()** of the **Callee** object to register a callback. This callback is invoked when the callee ability receives data from the caller ability. ![stage-call](figures/stage-call.png) -> **NOTE**
+> **NOTE** +> > The launch type of the callee ability must be **singleton**. +> > Currently, only system applications can use the ability call. ## Available APIs @@ -34,7 +36,7 @@ The table below describes the ability call APIs. For details, see [Ability](../r **Table 2** Ability call APIs |API|Description| |:------|:------| -|startAbilityByCall(want: Want): Promise\|Starts an ability in the foreground (through the **want** configuration) or background (default) and obtains the **Caller** object for communication with the ability. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartabilitybycall).| +|startAbilityByCall(want: Want): Promise\|Starts an ability in the foreground (through the **want** configuration) or background (default) and obtains the **Caller** object for communication with the ability. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md#abilitycontextstartabilitybycall) or **ServiceExtensionContext**.| |on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee ability registers a method.| |off(method: string): void|Callback invoked when the callee ability deregisters a method.| |call(method: string, data: rpc.Sequenceable): Promise\|Sends agreed sequenceable data to the callee ability.| @@ -210,22 +212,25 @@ function getRemoteDeviceId() { if (typeof dmClass === 'object' && dmClass != null) { var list = dmClass.getTrustedDeviceListSync() if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null") + console.log("EntryAbility onButtonClick getRemoteDeviceId err: list is null") return } - console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId) + console.log("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId) return list[0].deviceId } else { - console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null") + console.log("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null") } } ``` In the cross-device scenario, your application must also apply for the data synchronization permission from end users. The code snippet is as follows: ```ts +import abilityAccessCtrl from '@ohos.abilityAccessCtrl.d.ts'; + requestPermission() { let context = this.context let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] - context.requestPermissionsFromUser(permissions).then((data) => { + let atManager = abilityAccessCtrl.createAtManager(); + atManager.requestPermissionsFromUser(context, permissions).then((data) => { console.log("Succeed to request permission from user with data: "+ JSON.stringify(data)) }).catch((error) => { console.log("Failed to request permission from user with error: "+ JSON.stringify(error)) diff --git a/en/application-dev/ability-deprecated/stage-formextension.md b/en/application-dev/ability-deprecated/stage-formextension.md index c45b33732a4f902391eb153c9f5304b071bc4f34..bc1c54afe9d2e323f0938bca250f83737df9cbdb 100644 --- a/en/application-dev/ability-deprecated/stage-formextension.md +++ b/en/application-dev/ability-deprecated/stage-formextension.md @@ -2,32 +2,32 @@ ## Widget Overview -A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application. +A widget 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 displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message. +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. -Basic concepts: +Before you get started, it would be helpful if you have a basic understanding of the following concepts: -- Widget provider: an atomic service that controls what and how content is displayed in a widget and interacts with users. -- Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application. -- Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update. +- 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. +- 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. > **NOTE** > -> The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated. +> The widget host and provider do not need to be running all the time. The Widget Manager will start the widget provider to obtain widget information when a widget is added, deleted, or updated. -You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager. +You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager. -The widget provider controls the widget content to display, component layout, and click events bound to components. +The widget provider controls the widget content to display, the layout of components used in the widget, and click events bound to the components. ## When to Use -Stage widget development refers to the development conducted by the widget provider based on the [stage model](stage-brief.md). As a widget provider, you need to carry out the following operations: +Carry out the following operations to develop the widget provider based on the [stage model](stage-brief.md): -- Develop the lifecycle callbacks in **FormExtension**. -- Create a **FormBindingData** instance. -- Update a widget through **FormProvider**. -- Develop the widget UI page. +1. Implement lifecycle callbacks by using the **FormExtension** APIs. +2. Create a **FormBindingData** instance. +3. Update a widget by using the **FormProvider** APIs. +4. Develop the widget UI page. ## Available APIs @@ -37,12 +37,12 @@ The **FormExtension** class has the following APIs. For details, see [FormExtens | API | Description | | :----------------------------------------------------------- | :------------------------------------------- | -| onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a **Form** instance (widget) has been created. | +| onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a widget has been created. | | onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| | onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. | | onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility. | | onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event. | -| onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. | +| onDestroy(formId: string): void | Called to notify the widget provider that a widget has been destroyed. | | onConfigurationUpdated(config: Configuration): void; | Called when the configuration of the environment where the widget is running is updated. | The **FormExtension** class also has a member context, that is, the **FormExtensionContext** class. For details, see [FormExtensionContext](../reference/apis/js-apis-inner-application-formExtensionContext.md). @@ -54,7 +54,7 @@ The **FormExtension** class also has a member context, that is, the **FormExtens | startAbility(want: Want, callback: AsyncCallback<void>): void | Starts an ability. This API uses an asynchronous callback to return the result. (This is a system API and cannot be called by third-party applications.)| | startAbility(want: Want): Promise<void> | Starts an ability. This API uses a promise to return the result. (This is a system API and cannot be called by third-party applications.)| -For details, see [FormProvider](../reference/apis/js-apis-application-formProvider.md). +The table below describes the **FormProvider** APIs. For details, see [FormProvider](../reference/apis/js-apis-application-formProvider.md). **Table 3** FormProvider APIs @@ -69,18 +69,18 @@ For details, see [FormProvider](../reference/apis/js-apis-application-formProvid ### Creating a FormExtension Instance -To create a widget in the stage model, implement the lifecycle callbacks of **FormExtension**. The sample code is as follows: +To create a widget in the stage model, you need to implement lifecycle callbacks using the **FormExtension** APIs. The code snippet is as follows: 1. Import the required modules. ```javascript - import FormExtension from '@ohos.application.FormExtension' - import formBindingData from '@ohos.application.formBindingData' - import formInfo from '@ohos.application.formInfo' - import formProvider from '@ohos.application.formProvider' + import FormExtension from '@ohos.app.ability.FormExtension'; + import formBindingData from '@ohos.app.form.formBindingData'; + import formInfo from '@ohos.app.form.formInfo'; + import formProvider from '@ohos.app.form.formProvider'; ``` -2. Implement the lifecycle callbacks of **FormExtension**. +2. Implement lifecycle callbacks for the widget. ```javascript export default class FormAbility extends FormExtension { @@ -99,7 +99,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo console.log('FormAbility onCastToNormal'); } onUpdate(formId) { - // To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update. + // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. console.log('FormAbility onUpdate'); let obj = { "title": "titleOnUpdate", @@ -132,7 +132,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo - Configure Extension ability information under **extensionAbilities** in the **module.json5** file. The internal field structure is described as follows: - | Field | Description | Data Type | Default | + | Name | Description | Data Type | Default Value Allowed | | ----------- | ------------------------------------------------------------ | ---------- | -------------------- | | name | Name of the Extension ability. This field must be specified. | String | No | | srcEntrance | Path of the Extension ability lifecycle code. This field must be specified.| String | No | @@ -145,7 +145,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo For a Form Extension ability, you must specify **metadata**. Specifically, set **name** to **ohos.extension.form** (fixed), and set **resource** to the index of the widget configuration information. - A configuration example is as follows: + Example configuration: ```json "extensionAbilities": [{ @@ -165,24 +165,24 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo The internal field structure is described as follows: - | Field | Description | Data Type | Default | + | Name | Description | Data Type | Default Value Allowed | | ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ | - | name | Class name of a widget. The value is a string with a maximum of 127 bytes. | String | No | + | name | Class name of the 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. Available values are as follows:
**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. Available values are as follows:
**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 | + | 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. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is recommended.
**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.
This parameter has a lower priority than **updateDuration**. 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.
This parameter has a higher priority than **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number | Yes (initial value: **0**) | + | 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) | - A configuration example is as follows: + Example configuration: ```json { @@ -200,7 +200,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo "defaultDimension": "2*2", "updateEnabled": true, "scheduledUpdateTime": "10:30", - "formConfigAbility": "ability://ohos.samples.FormApplication.MainAbility" + "formConfigAbility": "ability://ohos.samples.FormApplication.EntryAbility" }] } ``` @@ -208,7 +208,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo ### Persistently Storing Widget Data -Mostly, the widget provider is started only when it needs to obtain 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 the widget. +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. ```javascript onCreate(want) { @@ -230,7 +230,7 @@ Mostly, the widget provider is started only when it needs to obtain information } ``` -You should override **onDestroy** to delete widget data. +You should override **onDestroy** to implement widget data deletion. ```javascript onDestroy(formId) { @@ -242,30 +242,30 @@ You should override **onDestroy** to delete widget data. } ``` -For details about the persistence method, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). +For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). -Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one. +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 that will be persistently used by the widget host +- Normal widget: a widget persistently used by the widget host -- Temporary widget: a widget that is temporarily used by the widget host +- Temporary widget: a widget temporarily used by the widget host -Data of a temporary widget is not persistently stored. If it is deleted from the Widget Manager due to exceptions, such as crash of the widget framework, the widget provider will not be notified of which widget is deleted, and still keeps the data. In light of this, the widget provider should implement data clearing. If the widget host successfully converts a temporary widget into a normal one, the widget provider should also process the widget ID and store the data persistently. This prevents the widget provider from deleting the widget data when clearing temporary widgets. +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 a widget application initiates a data update upon a scheduled or periodic update, the application obtains the latest data and calls **updateForm** to update the widget. The sample code is as follows: +When an application initiates a scheduled or periodic update, the application obtains the latest data and calls **updateForm** to update the widget. The code snippet is as follows: ```javascript onUpdate(formId) { - // To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update. + // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. console.log('FormAbility onUpdate'); 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. + // 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.log('FormAbility updateForm, error:' + JSON.stringify(error)); }); @@ -278,9 +278,9 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme > **NOTE** > -> Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI. +> Only the JavaScript-based web-like development paradigm is supported when developing the widget UI. - - In the HML file: + - HML file: ```html
@@ -295,7 +295,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
``` - - In the CSS file: + - CSS file: ```css .container { @@ -336,7 +336,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme } ``` - - In the JSON file: + - JSON file: ```json { "data": { @@ -346,7 +346,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme "actions": { "routerEvent": { "action": "router", - "abilityName": "MainAbility", + "abilityName": "EntryAbility", "params": { "message": "add detail" } @@ -363,18 +363,18 @@ Now you've got a widget shown below. 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 **onclick** in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. -2. For the router event, set the following attributes: - - **action**: **"router"**. - - **abilityName**: target ability name, for example, **MainAbility**, which is the default main ability name in DevEco Studio for the stage model. - - **params**: custom parameters of 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. For the message event, set the following attributes: - - **action**: **"message"**. +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**: target ability name, for example, **EntryAbility**, which is the default UIAbility name in DevEco Studio for the stage model. + - **params**: custom parameters of 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 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 **onEvent**. -The following is an example: +The code snippet is as follows: - - In the HML file: + - HML file: ```html
@@ -389,7 +389,7 @@ The following is an example:
``` - - In the JSON file: + - JSON file: ```json { "data": { @@ -399,7 +399,7 @@ The following is an example: "actions": { "routerEvent": { "action": "router", - "abilityName": "MainAbility", + "abilityName": "EntryAbility", "params": { "message": "add detail" } diff --git a/en/application-dev/ability-deprecated/stage-serviceextension.md b/en/application-dev/ability-deprecated/stage-serviceextension.md index 98cae5914f7afa34c916c53f6bb423b590cf5070..aee8f9c8116dffb49956a2bb9a1cad2ad263a166 100644 --- a/en/application-dev/ability-deprecated/stage-serviceextension.md +++ b/en/application-dev/ability-deprecated/stage-serviceextension.md @@ -42,9 +42,9 @@ OpenHarmony does not support creation of a Service Extension ability for third-p 2. Customize a class that inherits from `ServiceExtensionAbility` in the .ts file in the directory where the Service Extension ability is defined (`entry\src\main\ets\ServiceExtAbility\ServiceExtAbility.ts` by default) and override the lifecycle callbacks of the base class. The code sample is as follows: ```js - import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility' - import rpc from '@ohos.rpc' - + import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; + import rpc from '@ohos.rpc'; + class StubTest extends rpc.RemoteObject { constructor(des) { super(des); @@ -52,7 +52,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p onRemoteRequest(code, data, reply, option) { } } - + class ServiceExtAbility extends ServiceExtensionAbility { onCreate(want) { console.log('onCreate, want:' + want.abilityName); diff --git a/en/application-dev/ability-deprecated/wantagent.md b/en/application-dev/ability-deprecated/wantagent.md index 4b1854d1a54a36f864b3dd4215040eb24db2e5f3..0fc2036aac7d8b141310521a704570f28801f063 100644 --- a/en/application-dev/ability-deprecated/wantagent.md +++ b/en/application-dev/ability-deprecated/wantagent.md @@ -1,6 +1,6 @@ # WantAgent Development ## When to Use -The **WantAgent** class encapsulates want information that specifies a particular action, which can be starting an ability or publishing a common event. You can either call **wantAgent.trigger** to trigger a **WantAgent** directly or add a **WantAgent** to a notification so that it will be triggered when users tap the notification. +The **WantAgent** class encapsulates want information that specifies a particular action, which can be starting an ability or publishing a common event. You can either call **wantAgent.trigger** to trigger a **WantAgent** directly or add a **WantAgent** to a notification so that it will be triggered when users tap the notification. ## Available APIs | API | Description| @@ -12,13 +12,13 @@ The **WantAgent** class encapsulates want information that specifies a particula ## How to Develop 1. Import the **WantAgent** module. - ``` - import wantAgent from '@ohos.wantAgent'; + ```ts + import wantAgent from '@ohos.app.ability.wantAgent'; ``` 2. Create a **WantAgentInfo** object that will be used for starting an ability. For details about the data types and parameters of **WantAgentInfo**, see [WantAgent](../reference/apis/js-apis-wantAgent.md#wantagentinfo). - ``` + ```ts private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations. // wantAgentInfo @@ -27,7 +27,7 @@ The **WantAgent** class encapsulates want information that specifies a particula { deviceId: "", bundleName: "com.example.test", - abilityName: "com.example.test.MainAbility", + abilityName: "com.example.test.EntryAbility", action: "", entities: [], uri: "", @@ -42,7 +42,7 @@ The **WantAgent** class encapsulates want information that specifies a particula 3. Create a **WantAgentInfo** object for publishing a common event. - ``` + ```ts private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations. // wantAgentInfo @@ -61,7 +61,7 @@ The **WantAgent** class encapsulates want information that specifies a particula 4. Create a **WantAgent** object and save the returned **wantAgentObj** for subsequent trigger operations. - ``` + ```ts // Create a WantAgent object. wantAgent.getWantAgent(wantAgentInfo, (err, wantAgentObj) => { if (err.code) { @@ -75,7 +75,7 @@ The **WantAgent** class encapsulates want information that specifies a particula 5. Trigger the **WantAgent** object. - ``` + ```ts // Trigger the WantAgent object. var triggerInfo = { code:0 diff --git a/en/application-dev/application-models/widget-development-fa.md b/en/application-dev/application-models/widget-development-fa.md index df162455f63272a817d0a7773d150419011a7467..17f9ee7234865b5d01e2a5f68e52cf7928739db7 100644 --- a/en/application-dev/application-models/widget-development-fa.md +++ b/en/application-dev/application-models/widget-development-fa.md @@ -184,7 +184,7 @@ The widget configuration file is named **config.json**. Find the **config.json** | type | Type of the JavaScript component. The value can be:
**normal**: indicates an application instance.
**form**: indicates a widget instance.| String| Yes (initial value: **normal**)| | mode | Development mode of the JavaScript component.| Object| Yes (initial value: left empty)| - A configuration example is as follows: + Example configuration: ```json @@ -211,14 +211,14 @@ The widget configuration file is named **config.json**. Find the **config.json** | 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 attribute 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**)| + | 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)| | jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes.| String| No| - | metaData | Metadata of the widget. This attribute contains the array of the **customizeData** attribute.| Object| 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)| | customizeData | Custom information about the widget.| Object array| Yes (initial value: left empty)| - A configuration example is as follows: + Example configuration: ```json @@ -236,7 +236,7 @@ The widget configuration file is named **config.json**. Find the **config.json** "forms": [{ "colorMode": "auto", "defaultDimension": "2*2", - "description": "This is a service widget.", + "description": "This is a widget.", "formVisibleNotify": true, "isDefault": true, "jsComponentName": "widget", @@ -282,7 +282,7 @@ async function storeFormInfo(formId: string, formName: string, tempFlag: boolean 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 information for subsequent use, such as instance acquisition and update. + // Persistently store widget data for subsequent use, such as instance acquisition and update. // Implement this API based on project requirements. storeFormInfo(formId, formName, tempFlag); @@ -325,7 +325,7 @@ async function deleteFormInfo(formId: string) { For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). -The **Want** object passed by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. +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 @@ -451,12 +451,12 @@ You can set router and message events for components on a widget. The router eve 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. + - **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.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. + - **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 **onEvent**. The following is an example: diff --git a/en/application-dev/application-models/widget-development-stage.md b/en/application-dev/application-models/widget-development-stage.md index 32aa03e7aaea833a41b948764ca225c605adf24b..3e542956072a31fbc8dbca097ae264dfe8ebfc5f 100644 --- a/en/application-dev/application-models/widget-development-stage.md +++ b/en/application-dev/application-models/widget-development-stage.md @@ -181,7 +181,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo ### 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. - A configuration example is as follows: + Example configuration: ```json @@ -222,19 +222,19 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo | 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 attribute 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**)| + | 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 attribute contains the array of the **customizeData** attribute.| Object| 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)| - A configuration example is as follows: + Example configuration: ```json { "forms": [ { "name": "widget", - "description": "This is a service widget.", + "description": "This is a widget.", "src": "./js/widget/pages/index/index", "window": { "designWidth": 720, @@ -288,7 +288,7 @@ export default class EntryFormAbility extends FormExtension { 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 information for subsequent use, such as instance acquisition and update. + // Persistently store widget data for subsequent use, such as instance acquisition and update. // Implement this API based on project requirements. storeFormInfo(formId, formName, tempFlag); @@ -334,7 +334,7 @@ export default class EntryFormAbility extends FormExtension { For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). -The **Want** object passed by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. +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 @@ -462,12 +462,12 @@ 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. + - **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. + - **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: