提交 cecaa207 编写于 作者: G ge-yafang

update docs

Signed-off-by: Nge-yafang <geyafang@huawei.com>
# Ability Development # Ability Development
- [Ability Framework Overview](ability-brief.md) - [FA Model Overview](fa-brief.md)
- FA Model - [Page Ability Development](fa-pageability.md)
- [FA Model Overview](fa-brief.md) - [Service Ability Development](fa-serviceability.md)
- [Page Ability Development](fa-pageability.md) - [Data Ability Development](fa-dataability.md)
- [Service Ability Development](fa-serviceability.md) - [FA Widget Development](fa-formability.md)
- [Data Ability Development](fa-dataability.md)
- [FA Widget Development](fa-formability.md)
- Other - Other
- [Ability Assistant Usage](ability-assistant-guidelines.md) - [Ability Assistant Usage](ability-assistant-guidelines.md)
# Ability Framework Overview
An ability is an abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more **Ability** instances.
The ability framework model has two forms. The first form is the FA model, which applies to application development using API 8 and earlier versions. In the FA model, there are Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service and Data abilities. The stage model is introduced since API 9. In the stage model, there are Page abilities and Extension abilities. The Extension ability is further extended to Service Extension, Form Extension, Data Share Extension, and more.
The stage model is designed to make complex application development easier in a distributed environment. The two models have differences in the following aspects:
* Ability type and API usage
![favsstage](figures/favsstage.png)
* Ability lifecycle
![lifecycle](figures/lifecycle.png)
* Application configuration files and application package structure (The differences are reflected in the application packages generated by the IDE.)
For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md).
...@@ -2,9 +2,9 @@ ...@@ -2,9 +2,9 @@
The application development documents provide reference for you to develop applications using the APIs provided by OpenHarmony. The documents provided walk you through how to use JavaScript \(JS\) APIs to develop applications on the standard system. The application development documents provide reference for you to develop applications using the APIs provided by OpenHarmony. The documents provided walk you through how to use JavaScript \(JS\) APIs to develop applications on the standard system.
To get a glimpse of the basic methods for developing applications, see [Basics](quick-start/Readme-EN.md). For details about the API list and references, see [Reference](reference/Readme-EN.md). To get a glimpse of the basic methods for developing applications, see [Basics](quick-start/start-overview.md). For details about the API list and references, see [Reference](reference/apis/js-apis-featureAbility.md).
To better understand frequently used modules, see the development guidelines for [UI](ui/Readme-EN.md), [Media](media/Readme-EN.md), and [Connectivity](connectivity/Readme-EN.md). To better understand frequently used modules, see the development guidelines for [Ability](ability/fa-brief.md), [UI](ui/arkui-overview.md), [Media](media/Readme-EN.md), etc.
For details about the principles and basic information of each subsystem, see the README file in **docs/en/readme**. For details about the principles and basic information of each subsystem, see the README file in **docs/en/readme**.
- [Application Development Overview](application-dev-guide.md) - [Application Development Overview](application-dev-guide.md)
- Quick Start - Quick Start
- [Directory Structure](quick-start/package-structure.md) - [Directory Structure](quick-start/package-structure.md)
- [Resource File Categories](quick-start/basic-resource-file-categories.md) - [Resource File Categories](quick-start/basic-resource-file-categories.md)
- Development - Development
- [Ability Development](ability/Readme-EN.md) - [Ability Development](ability/Readme-EN.md)
- [Ability Framework Overview](ability/ability-brief.md) - [FA Model Overview](ability/fa-brief.md)
- FA Model - [Page Ability Development](ability/fa-pageability.md)
- [FA Model Overview](ability/fa-brief.md) - [Service Ability Development](ability/fa-serviceability.md)
- [Page Ability Development](ability/fa-pageability.md) - [Data Ability Development](ability/fa-dataability.md)
- [Service Ability Development](ability/fa-serviceability.md) - [FA Widget Development](ability/fa-formability.md)
- [Data Ability Development](ability/fa-dataability.md)
- [FA Widget Development](ability/fa-formability.md)
- Other - Other
- [Ability Assistant Usage](ability/ability-assistant-guidelines.md) - [Ability Assistant Usage](ability/ability-assistant-guidelines.md)
- [UI](ui/Readme-EN.md) - [UI](ui/Readme-EN.md)
- [ArkUI Overview](arkui-overview.md) - [ArkUI Overview](arkui-overview.md)
- JavaScript-based Web-Like Development Paradigm - JavaScript-based Web-Like Development Paradigm
...@@ -129,6 +129,7 @@ ...@@ -129,6 +129,7 @@
- [Building a Food Category List Layout](ui/ui-ts-building-category-list-layout.md) - [Building a Food Category List Layout](ui/ui-ts-building-category-list-layout.md)
- [Building a Food Category Grid Layout](ui/ui-ts-building-category-grid-layout.md) - [Building a Food Category Grid Layout](ui/ui-ts-building-category-grid-layout.md)
- [Implementing Page Redirection and Data Transmission](ui/ui-ts-page-redirection-data-transmission.md) - [Implementing Page Redirection and Data Transmission](ui/ui-ts-page-redirection-data-transmission.md)
- Basic Functions - Basic Functions
- Window Manager - Window Manager
- Window - Window
...@@ -209,10 +210,13 @@ ...@@ -209,10 +210,13 @@
- Distributed Call Chain Tracing - Distributed Call Chain Tracing
- [Overview of Distributed Call Chain Tracing](dfx/hitracechain-overview.md) - [Overview of Distributed Call Chain Tracing](dfx/hitracechain-overview.md)
- [Development of Distributed Call Chain Tracing](dfx/hitracechain-guidelines.md) - [Development of Distributed Call Chain Tracing](dfx/hitracechain-guidelines.md)
- Tools - Tools
- [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md)
- Hands-On Tutorials - Hands-On Tutorials
- [Samples](https://gitee.com/openharmony/app_samples/blob/master/README.md) - [Samples](https://gitee.com/openharmony/app_samples/blob/master/README.md)
- API References - API References
- Compent Reference (JavaScript-based Web-like Development Paradigm) - Compent Reference (JavaScript-based Web-like Development Paradigm)
- Components - Components
......
...@@ -37,11 +37,11 @@ ...@@ -37,11 +37,11 @@
- [Public File Access and Management](js-apis-filemanager.md) - [Public File Access and Management](js-apis-filemanager.md)
- [App Storage Statistics](js-apis-storage-statistics.md) - [App Storage Statistics](js-apis-storage-statistics.md)
- [Volume Management](js-apis-volumemanager.md) - [Volume Management](js-apis-volumemanager.md)
- Account Management - Account Management
- [OS Account Management](js-apis-osAccount.md) - [OS Account Management](js-apis-osAccount.md)
- [Distributed Account Management](js-apis-distributed-account.md) - [Distributed Account Management](js-apis-distributed-account.md)
- [App Account Management](js-apis-appAccount.md) - [App Account Management](js-apis-appAccount.md)
- Telephony Service - Telephony Service
- [Call](js-apis-call.md) - [Call](js-apis-call.md)
- [SMS](js-apis-sms.md) - [SMS](js-apis-sms.md)
- [SIM Management](js-apis-sim.md) - [SIM Management](js-apis-sim.md)
......
# Work Scheduler Callbacks
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'
```
## WorkSchedulerExtensionAbility.onWorkStart
- **System capability**
SystemCapability.ResourceSchedule.WorkScheduler
- **API**
onWorkStart(workInfo: WorkInfo);
- **Description**
Triggered when the Work Scheduler task starts.
- **Example**
```
export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility {
onWorkStart(workInfo) {
console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo));
}
}
```
## WorkSchedulerExtensionAbility.onWorkStop
- **System capability**
SystemCapability.ResourceSchedule.WorkScheduler
- **API**
onWorkStop(workInfo: WorkInfo);
- **Description**
Triggered when the Work Scheduler task stops.
- **Example**
```
export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility {
onWorkStop(workInfo) {
console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo));
}
}
```
...@@ -434,18 +434,6 @@ Enumerates the interrupt types. ...@@ -434,18 +434,6 @@ Enumerates the interrupt types.
| INTERRUPT_TYPE_BEGIN | 1 | Audio playback interruption started. | | INTERRUPT_TYPE_BEGIN | 1 | Audio playback interruption started. |
| INTERRUPT_TYPE_END | 2 | Audio playback interruption ended. | | INTERRUPT_TYPE_END | 2 | Audio playback interruption ended. |
## InterruptForceType<sup>9+</sup>
Enumerates the interrupt force types.
**System capability:** SystemCapability.Multimedia.Audio.Renderer
| Name | Default Value | Description |
| :-------------- | :------------ | :----------------------------------------- |
| INTERRUPT_FORCE | 0 | Forced action taken by system. |
| INTERRUPT_SHARE | 1 | App can choose to take action or ignore. |
## InterruptHint ## InterruptHint
Enumerates the interrupt hints. Enumerates the interrupt hints.
...@@ -542,20 +530,6 @@ Describes audio capturer configuration options. ...@@ -542,20 +530,6 @@ Describes audio capturer configuration options.
| streamInfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Stream information. | | streamInfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Stream information. |
| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | Capturer information. | | capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | Capturer information. |
## InterruptEvent<sup>9+</sup>
Describes the interrupt event received by the app when playback is interrupted.
**System capability:** SystemCapability.Multimedia.Audio.Renderer
**Parameters:**
| Name | Type | Mandatory | Description |
| :-------- | :-------------------------------------------- | :-------- | :---------------------------------------------------------------- |
| eventType | [InterruptType](#interrupttype) | Yes | Whether the interruption has started or finished. |
| forceType | [InterruptForceType](#interruptforcetype9) | Yes | Whether the action is taken by system or to be taken by the app. |
| hintType | [InterruptHint](#interrupthint) | Yes | Type of action. |
## AudioInterrupt ## AudioInterrupt
The parameters passed in by the audio listener event. The parameters passed in by the audio listener event.
...@@ -2560,52 +2534,6 @@ audioRenderer.getRenderRate().then((renderRate) => { ...@@ -2560,52 +2534,6 @@ audioRenderer.getRenderRate().then((renderRate) => {
}); });
``` ```
### on('interrupt')<sup>9+</sup>
on(type: 'interrupt', callback: Callback\<InterruptEvent>): void
Subscribes to audio interrupt events. This API uses a callback to get interrupt events. The interrupt event is triggered when audio rendering is interrupted.
**System capability:** SystemCapability.Multimedia.Audio.Renderer
**Parameters:**
| Name | Type | Mandatory | Description |
| :------- | :-------------------------------------------- | :-------- | :---------------------------------------------- |
| type | string | Yes | Type of the playback event to subscribe to. |
| callback | Callback<[InterruptEvent](#interruptevent9)\> | Yes | Callback used to listen for interrupt callback. |
**Example:**
```
audioRenderer.on('interrupt', (interruptEvent) => {
if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
switch (interruptEvent.hintType) {
case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
console.log('Force paused. Stop writing');
isPlay = false;
break;
case audio.InterruptHint.INTERRUPT_HINT_STOP:
console.log('Force stopped. Stop writing');
isPlay = false;
break;
}
} else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
switch (interruptEvent.hintType) {
case audio.InterruptHint.INTERRUPT_HINT_RESUME:
console.log('Resume force paused renderer or ignore');
startRenderer();
break;
case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
console.log('Choose to pause or ignore');
pauseRenderer();
break;
}
}
});
```
### on('markReach')<sup>8+</sup> ### on('markReach')<sup>8+</sup>
on(type: 'markReach', frame: number, callback: (position: number) => {}): void on(type: 'markReach', frame: number, callback: (position: number) => {}): void
......
# Work Scheduler
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```
import workScheduler from '@ohos.workScheduler'
```
## workScheduler.startWork
startWork(work: WorkInfo): boolean
Instructs the **WorkSchedulerService** to add the specified task to the execution queue.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | --------------------- | ---- | -------------- |
| work | [WorkInfo](#workinfo) | Yes | Task to be added to the execution queue.|
**Return value**
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the task is added to the execution queue; returns **false** otherwise.|
**Example**
```
let workInfo = {
workId: 1,
batteryLevel:50,
batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
isRepeat: false,
isPersisted: true,
bundleName: "com.example.myapplication",
abilityName: "MyExtension"
}
var res = workScheduler.startWork(workInfo);
console.info("workschedulerLog res:" + res);
```
## workScheduler.stopWork
stopWork(work: WorkInfo, needCancel?: boolean): boolean
Instructs the **WorkSchedulerService** to stop the specified task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Parameters**
| Name | Type | Mandatory | Description |
| ---------- | --------------------- | ---- | ---------- |
| work | [WorkInfo](#workinfo) | Yes | Task to stop. |
| needCancel | boolean | Yes | Whether to cancel the task.|
**Return value**
| Type | Description |
| ------- | ----------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```
let workInfo = {
workId: 1,
batteryLevel:50,
batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
isRepeat: false,
isPersisted: true,
bundleName: "com.example.myapplication",
abilityName: "MyExtension"
}
var res = workScheduler.stopWork(workInfo, false);
console.info("workschedulerLog res:" + res);
```
## workScheduler.getWorkStatus
getWorkStatus(workId: number, callback : AsyncCallback\<WorkInfo>): void
Obtains the latest task status. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------- |
| workId | number | Yes | Task ID. |
| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; returns **null** otherwise.|
**Example**
```
workScheduler.getWorkStatus(50, (err, res) => {
if (err) {
console.info('workschedulerLog getWorkStatus failed, because:' + err.data);
} else {
for (let item in res) {
console.info('workschedulerLog getWorkStatus success,' + item + ' is:' + res[item]);
}
}
});
```
## workScheduler.getWorkStatus
getWorkStatus(workId: number): Promise\<WorkInfo>
Obtains the latest task status. This API uses a promise to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | -------- |
| workId | number | Yes | Task ID.|
**Return value**
| Type | Description |
| ------------------------------- | ---------------------------------------- |
| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; returns **null** otherwise.|
**Example**
```
workScheduler.getWorkStatus(50).then((res) => {
for (let item in res) {
console.info('workschedulerLog getWorkStatus success,' + item + ' is:' + res[item]);
}
}).catch((err) => {
console.info('workschedulerLog getWorkStatus failed, because:' + err.data);
})
```
## workScheduler.obtainAllWorks
obtainAllWorks(callback : AsyncCallback\<void>): Array\<WorkInfo>
Obtains all tasks associated with this application. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ------------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return all tasks associated with the current application.|
**Return value**
| Type | Description |
| ----------------------------- | --------------- |
| Array\<[WorkInfo](#workinfo)> | All tasks associated with the current application.|
**Example**
```
workScheduler.obtainAllWorks((err, res) =>{
if (err) {
console.info('workschedulerLog obtainAllWorks failed, because:' + err.data);
} else {
console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res));
}
});
```
## workScheduler.obtainAllWorks
obtainAllWorks(): Promise<Array\<WorkInfo>>
Obtains all tasks associated with this application. This API uses a promise to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Return value**
| Type | Description |
| -------------------------------------- | ------------------------------ |
| Promise<Array\<[WorkInfo](#workinfo)>> | Promise used to return all tasks associated with the current application.|
**Example**
```
workScheduler.obtainAllWorks().then((res) => {
console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res));
}).catch((err) => {
console.info('workschedulerLog obtainAllWorks failed, because:' + err.data);
})
```
## workScheduler.stopAndClearWorks
stopAndClearWorks(): boolean
Stops and cancels all tasks associated with the current application.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Example**
```
let res = workScheduler.stopAndClearWorks();
console.info("workschedulerLog res:" + res);
```
## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean
Checks whether the last execution of the specified task timed out. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ---------------------------------------- |
| workId | number | Yes | Task ID. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.|
**Example**
```
workScheduler.isLastWorkTimeOut(500, (err, res) =>{
if (err) {
console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.data);
} else {
console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res);
}
});
```
## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number): Promise\<boolean>
Checks whether the last execution of the specified task timed out. This API uses a promise to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | -------- |
| workId | number | Yes | Task ID.|
**Return value**
| Type | Description |
| ----------------- | ---------------------------------------- |
| Promise\<boolean> | Promise used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.|
**Example**
```
workScheduler.isLastWorkTimeOut(500)
.then(res => {
console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res);
})
.catch(err => {
console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.data);
});
```
## WorkInfo
Provides detailed information about the task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
| Name | Type | Mandatory | Description |
| --------------- | --------------------------------- | ---- | ---------------- |
| workId | number | Yes | Task ID. |
| bundleName | string | Yes | Name of the Work Scheduler task bundle. |
| abilityName | string | Yes | Name of the component to be notified by a Work Scheduler callback.|
| networkType | [NetworkType](#networktype) | No | Network type. |
| isCharging | boolean | No | Whether the device is charging. |
| chargerType | [ChargingType](#chargingtype) | No | Charging type. |
| batteryLevel | number | No | Battery level. |
| batteryStatus | [BatteryStatus](#batterystatus) | No | Battery status. |
| storageRequest | [StorageRequest](#storagerequest) | No | Storage status. |
| isRepeat | boolean | No | Whether the task is repeated. |
| repeatCycleTime | number | No | Repeat interval. |
| repeatCount | number | No | Number of repeat times. |
## NetworkType
Enumerates the network types that can trigger the task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
| Name | Default Value | Description |
| ---------------------- | ---- | ----------------------- |
| NETWORK_TYPE_ANY | 0 | Any network type. |
| NETWORK_TYPE_MOBILE | 1 | Mobile network. |
| NETWORK_TYPE_WIFI | 2 | Wi-Fi network. |
| NETWORK_TYPE_BLUETOOTH | 3 | Bluetooth network.|
| NETWORK_TYPE_WIFI_P2P | 4 | Wi-Fi P2P network. |
| NETWORK_TYPE_ETHERNET | 5 | Ethernet. |
## ChargingType
Enumerates the charging types that can trigger the task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
| Name | Default Value | Description |
| ------------------------- | ---- | -------------------- |
| CHARGING_PLUGGED_ANY | 0 | Any charging type.|
| CHARGING_PLUGGED_AC | 1 | DC charging. |
| CHARGING_PLUGGED_USB | 2 | USB charging. |
| CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. |
## BatteryStatus
Enumerates the battery status that can trigger the task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
| Name | Default Value | Description |
| -------------------------- | ---- | -------------------------- |
| BATTERY_STATUS_LOW | 0 | A low battery alert is displayed. |
| BATTERY_STATUS_OKAY | 1 | The battery level is restored from low to normal. |
| BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.|
## StorageRequest
Enumerates the storage status that can trigger the task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
|Name |Default Value |Description|
| -------- | -------- | -------- |
|STORAGE_LEVEL_LOW |0 |The storage space is insufficient.
|STORAGE_LEVEL_OKAY |1 |The storage space is restored from insufficient to normal.
|STORAGE_LEVEL_LOW_OR_OKAY |2 |The storage space is restored from insufficient to normal, or the storage space is insufficient.
...@@ -60,6 +60,7 @@ ...@@ -60,6 +60,7 @@
- [ImageAnimator](ts-basic-components-imageanimator.md) - [ImageAnimator](ts-basic-components-imageanimator.md)
- [LoadingProgress](ts-basic-components-loadingprogress.md) - [LoadingProgress](ts-basic-components-loadingprogress.md)
- [Marquee](ts-basic-components-marquee.md) - [Marquee](ts-basic-components-marquee.md)
- [Navigation](ts-basic-components-navigation.md)
- [PatternLock](ts-basic-components-patternlock.md) - [PatternLock](ts-basic-components-patternlock.md)
- [PluginComponent](ts-basic-components-plugincomponent.md) - [PluginComponent](ts-basic-components-plugincomponent.md)
- [Progress](ts-basic-components-progress.md) - [Progress](ts-basic-components-progress.md)
...@@ -67,6 +68,9 @@ ...@@ -67,6 +68,9 @@
- [Radio](ts-basic-components-radio.md) - [Radio](ts-basic-components-radio.md)
- [Rating](ts-basic-components-rating.md) - [Rating](ts-basic-components-rating.md)
- [RichText](ts-basic-components-richtext.md) - [RichText](ts-basic-components-richtext.md)
- [Stepper](ts-basic-components-stepper.md)
- [StepperItem](ts-basic-components-stepperitem.md)
- [ScrollBar](ts-basic-components-scrollbar.md)
- [Search](ts-basic-components-search.md) - [Search](ts-basic-components-search.md)
- [Select](ts-basic-components-select.md) - [Select](ts-basic-components-select.md)
- [Slider](ts-basic-components-slider.md) - [Slider](ts-basic-components-slider.md)
...@@ -94,17 +98,14 @@ ...@@ -94,17 +98,14 @@
- [List](ts-container-list.md) - [List](ts-container-list.md)
- [ListItem](ts-container-listitem.md) - [ListItem](ts-container-listitem.md)
- [Navigator](ts-container-navigator.md) - [Navigator](ts-container-navigator.md)
- [Navigation](ts-basic-components-navigation.md) -
- [Panel](ts-container-panel.md) - [Panel](ts-container-panel.md)
- [Refresh](ts-container-refresh.md) - [Refresh](ts-container-refresh.md)
- [Row](ts-container-row.md) - [Row](ts-container-row.md)
- [RowSplit](ts-container-rowsplit.md) - [RowSplit](ts-container-rowsplit.md)
- [Scroll](ts-container-scroll.md) - [Scroll](ts-container-scroll.md)
- [ScrollBar](ts-basic-components-scrollbar.md)
- [SideBarContainer](ts-container-sidebarcontainer.md) - [SideBarContainer](ts-container-sidebarcontainer.md)
- [Stack](ts-container-stack.md) - [Stack](ts-container-stack.md)
- [Stepper](ts-basic-components-stepper.md)
- [StepperItem](ts-basic-components-stepperitem.md)
- [Swiper](ts-container-swiper.md) - [Swiper](ts-container-swiper.md)
- [Tabs](ts-container-tabs.md) - [Tabs](ts-container-tabs.md)
- [TabContent](ts-container-tabcontent.md) - [TabContent](ts-container-tabcontent.md)
......
# OpenHarmony Application Development Documentation # OpenHarmony Application Development Documentation
- [Application Development Overview](application-dev-guide.md) - [Application Development Overview](application-dev-guide.md)
- Quick Start - Quick Start
- [Directory Structure](quick-start/package-structure.md) - [Directory Structure](quick-start/package-structure.md)
- [Resource File Categories](quick-start/basic-resource-file-categories.md) - [Resource File Categories](quick-start/basic-resource-file-categories.md)
- Development - Development
- [Ability Development](ability/Readme-EN.md) - [Ability Development](ability/Readme-EN.md)
- [Ability Framework Overview](ability/ability-brief.md)
- FA Model - [FA Model Overview](ability/fa-brief.md)
- [FA Model Overview](ability/fa-brief.md) - [Page Ability Development](ability/fa-pageability.md)
- [Page Ability Development](ability/fa-pageability.md) - [Service Ability Development](ability/fa-serviceability.md)
- [Service Ability Development](ability/fa-serviceability.md) - [Data Ability Development](ability/fa-dataability.md)
- [Data Ability Development](ability/fa-dataability.md) - [FA Widget Development](ability/fa-formability.md)
- [FA Widget Development](ability/fa-formability.md)
- Other - Other
- [Ability Assistant Usage](ability/ability-assistant-guidelines.md) - [Ability Assistant Usage](ability/ability-assistant-guidelines.md)
- [UI](ui/Readme-EN.md) - [UI](ui/Readme-EN.md)
- [ArkUI Overview](arkui-overview.md) - [ArkUI Overview](arkui-overview.md)
- JavaScript-based Web-Like Development Paradigm - JavaScript-based Web-Like Development Paradigm
...@@ -130,6 +132,7 @@ ...@@ -130,6 +132,7 @@
- [Building a Food Category List Layout](ui/ui-ts-building-category-list-layout.md) - [Building a Food Category List Layout](ui/ui-ts-building-category-list-layout.md)
- [Building a Food Category Grid Layout](ui/ui-ts-building-category-grid-layout.md) - [Building a Food Category Grid Layout](ui/ui-ts-building-category-grid-layout.md)
- [Implementing Page Redirection and Data Transmission](ui/ui-ts-page-redirection-data-transmission.md) - [Implementing Page Redirection and Data Transmission](ui/ui-ts-page-redirection-data-transmission.md)
- Basic Functions - Basic Functions
- Window Manager - Window Manager
- Window - Window
...@@ -210,10 +213,13 @@ ...@@ -210,10 +213,13 @@
- Distributed Call Chain Tracing - Distributed Call Chain Tracing
- [Overview of Distributed Call Chain Tracing](dfx/hitracechain-overview.md) - [Overview of Distributed Call Chain Tracing](dfx/hitracechain-overview.md)
- [Development of Distributed Call Chain Tracing](dfx/hitracechain-guidelines.md) - [Development of Distributed Call Chain Tracing](dfx/hitracechain-guidelines.md)
- Tools - Tools
- [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md)
- Hands-On Tutorials - Hands-On Tutorials
- [Samples](https://gitee.com/openharmony/app_samples/blob/master/README.md) - [Samples](https://gitee.com/openharmony/app_samples/blob/master/README.md)
- API References - API References
- Compent Reference (JavaScript-based Web-like Development Paradigm) - Compent Reference (JavaScript-based Web-like Development Paradigm)
- Components - Components
...@@ -376,6 +382,7 @@ ...@@ -376,6 +382,7 @@
- [ImageAnimator](reference/arkui-ts/ts-basic-components-imageanimator.md) - [ImageAnimator](reference/arkui-ts/ts-basic-components-imageanimator.md)
- [LoadingProgress](reference/arkui-ts/ts-basic-components-loadingprogress.md) - [LoadingProgress](reference/arkui-ts/ts-basic-components-loadingprogress.md)
- [Marquee](reference/arkui-ts/ts-basic-components-marquee.md) - [Marquee](reference/arkui-ts/ts-basic-components-marquee.md)
- [Navigation](reference/arkui-ts/ts-basic-components-navigation.md)
- [PatternLock](reference/arkui-ts/ts-basic-components-patternlock.md) - [PatternLock](reference/arkui-ts/ts-basic-components-patternlock.md)
- [PluginComponent](reference/arkui-ts/ts-basic-components-plugincomponent.md) - [PluginComponent](reference/arkui-ts/ts-basic-components-plugincomponent.md)
- [Progress](reference/arkui-ts/ts-basic-components-progress.md) - [Progress](reference/arkui-ts/ts-basic-components-progress.md)
...@@ -383,6 +390,7 @@ ...@@ -383,6 +390,7 @@
- [Radio](reference/arkui-ts/ts-basic-components-radio.md) - [Radio](reference/arkui-ts/ts-basic-components-radio.md)
- [Rating](reference/arkui-ts/ts-basic-components-rating.md) - [Rating](reference/arkui-ts/ts-basic-components-rating.md)
- [RichText](reference/arkui-ts/ts-basic-components-richtext.md) - [RichText](reference/arkui-ts/ts-basic-components-richtext.md)
- [ScrollBar](reference/arkui-ts/ts-basic-components-scrollbar.md)
- [Search](reference/arkui-ts/ts-basic-components-search.md) - [Search](reference/arkui-ts/ts-basic-components-search.md)
- [Select](reference/arkui-ts/ts-basic-components-select.md) - [Select](reference/arkui-ts/ts-basic-components-select.md)
- [Slider](reference/arkui-ts/ts-basic-components-slider.md) - [Slider](reference/arkui-ts/ts-basic-components-slider.md)
...@@ -412,13 +420,11 @@ ...@@ -412,13 +420,11 @@
- [List](reference/arkui-ts/ts-container-list.md) - [List](reference/arkui-ts/ts-container-list.md)
- [ListItem](reference/arkui-ts/ts-container-listitem.md) - [ListItem](reference/arkui-ts/ts-container-listitem.md)
- [Navigator](reference/arkui-ts/ts-container-navigator.md) - [Navigator](reference/arkui-ts/ts-container-navigator.md)
- [Navigation](reference/arkui-ts/ts-basic-components-navigation.md)
- [Panel](reference/arkui-ts/ts-container-panel.md) - [Panel](reference/arkui-ts/ts-container-panel.md)
- [Refresh](reference/arkui-ts/ts-container-refresh.md) - [Refresh](reference/arkui-ts/ts-container-refresh.md)
- [Row](reference/arkui-ts/ts-container-row.md) - [Row](reference/arkui-ts/ts-container-row.md)
- [RowSplit](reference/arkui-ts/ts-container-rowsplit.md) - [RowSplit](reference/arkui-ts/ts-container-rowsplit.md)
- [Scroll](reference/arkui-ts/ts-container-scroll.md) - [Scroll](reference/arkui-ts/ts-container-scroll.md)
- [ScrollBar](reference/arkui-ts/ts-basic-components-scrollbar.md)
- [SideBarContainer](reference/arkui-ts/ts-container-sidebarcontainer.md) - [SideBarContainer](reference/arkui-ts/ts-container-sidebarcontainer.md)
- [Stack](reference/arkui-ts/ts-container-stack.md) - [Stack](reference/arkui-ts/ts-container-stack.md)
- [Swiper](reference/arkui-ts/ts-container-swiper.md) - [Swiper](reference/arkui-ts/ts-container-swiper.md)
......
...@@ -384,15 +384,9 @@ ...@@ -384,15 +384,9 @@
- [HiSysEvent Tool Usage](subsystems/subsys-dfx-hisysevent-tool.md) - [HiSysEvent Tool Usage](subsystems/subsys-dfx-hisysevent-tool.md)
- Featured Topics - Featured Topics
- HPM Bundle - HPM Bundle
- [Development Specifications](bundles/bundles-standard-rules.md) - [HPM Part Overview](bundles/hpm-part-about.md)
- Development Guidelines - [HPM Part Development](bundles/hpm-part-development.md)
- [Bundle Development](bundles/bundles-guide-overview.md) - [HPM Part Reference](bundles/hpm-part-reference.md)
- [Preparations](bundles/bundles-guide-prepare.md)
- [Bundle Development](bundles/bundles-guide-develop.md)
- HPM User Guide
- [Introduction](bundles/bundles-demo-hpmdescription.md)
- [Preparations](bundles/bundles-demo-environment.md)
- [Development Example](bundles/bundles-demo-devsample.md)
- Device Development Examples - Device Development Examples
- [Mini- and Small-System Devices](guide/device-lite.md) - [Mini- and Small-System Devices](guide/device-lite.md)
- [WLAN-connected Products](guide/device-wlan.md) - [WLAN-connected Products](guide/device-wlan.md)
......
# Ability开发 # Ability开发
- [Ability框架概述](ability-brief.md) - [FA模型综述](fa-brief.md)
- FA模型 - [PageAbility开发指导](fa-pageability.md)
- [FA模型综述](fa-brief.md) - [ServiceAbility开发指导](fa-serviceability.md)
- [PageAbility开发指导](fa-pageability.md) - [DataAbility开发指导](fa-dataability.md)
- [ServiceAbility开发指导](fa-serviceability.md) - [FA卡片开发指导](fa-formability.md)
- [DataAbility开发指导](fa-dataability.md) - 其他
- [FA卡片开发指导](fa-formability.md) - [WantAgent开发指导](wantagent.md)
- Stage模型 - [Ability助手使用指导](ability-assistant-guidelines.md)
- [Stage模型综述](stage-brief.md) - [测试框架使用指导](ability-delegator.md)
- [Ability开发指导](stage-ability.md)
- [ServiceExtensionAbility开发指导](stage-serviceextension.md)
- [跨端迁移开发指导](stage-ability-continuation.md)
- [Call调用开发指导](stage-call.md)
- [Stage卡片开发指导](stage-formextension.md)
- 其他
- [WantAgent开发指导](wantagent.md)
- [Ability助手使用指导](ability-assistant-guidelines.md)
- [测试框架使用指导](ability-delegator.md)
# Ability框架概述
​ Ability是应用所具备能力的抽象,也是应用程序的重要组成部分。Ability是系统调度应用的最小单元,是能够完成一个独立功能的组件,一个应用可以包含一个或多个Ability。
​ Ability框架模型结构具有两种框架形态:
- 第一种形态为FA模型。API 8及其更早版本的应用程序只能使用FA模型进行开发。 FA模型将Ability分为FA(Feature Ability)和PA(Particle Ability)两种类型,其中FA支持Page Ability,PA支持Service Ability、Data Ability、以及FormAbility。
- 第二种形态为Stage模型。从API 9开始,Ability框架引入了Stage模型作为第二种应用框架形态,Stage模型将Ability分为Ability和ExtensionAbility两大类,其中ExtensionAbility又被扩展为ServiceExtensionAbility、FormExtensionAbility、DataShareExtensionAbility等等一系列ExtensionAbility,以便满足更多的使用场景。
​ Stage模型的设计,主要是为了方便开发者更加方便地开发出分布式环境下的复杂应用。下表给出了两种模型在设计上的差异:
| 对比 | FA模型 | Stage模型 |
| -------------- | ------------------------------------------------------------ | -------------------------------------------------------- |
| 开发方式 | 提供类Web的 api,UI开发与Stage模型一致。 | 提供面向对象的开发方式,UI开发与FA模型一致。 |
| 引擎实例 | 每个进程内的每个Ability独享一个JS VM引擎实例。 | 每个进程内的多个Ability实例共享一个JS VM引擎实例。 |
| 进程内对象共享 | 不支持。 | 支持。 |
| 包描述文件 | 使用config.json描述HAP包和组件信息,组件必须使用固定的文件名。 | 使用module.json描述HAP包和组件信息,可以指定入口文件名。 |
| 组件 | 提供PageAbility(页面展示),ServiceAbility(服务),DataAbility(数据分享), FormAbility(卡片)。 | 提供Ability(页面展示)、Extension(基于场景的服务扩展)。 |
​ 除了上述设计上的差异外,对于开发者而言,两种模型的主要区别在于:
* Ability类型存在差异;
![favsstage](figures/favsstage.png)
* Ability生命周期存在差异;
![lifecycle](figures/lifecycle.png)
​ 两种模型的基本介绍,详见[FA模型综述](fa-brief.md)[Stage模型综述](stage-brief.md)
\ No newline at end of file
# FA模型综述 # Ability综述
## 整体架构 ## 整体架构
OpenHarmony用户程序的开发本质上就是开发Ability。OpenHarmony系统是通过对Ability调度,结合系统提供的一致性调度契约对Ability进行生命周期管理,从而实现对用户程序的调度。 OpenHarmony用户程序的开发本质上就是开发Ability。OpenHarmony系统是通过对Ability调度,结合系统提供的一致性调度契约对Ability进行生命周期管理,从而实现对用户程序的调度。
......
# 跨端迁移开发指导
## 场景介绍
迁移的主要工作是实现将应用当前任务,包括页面控件状态变量、分布式对象等,迁移到远端设备。页面控件状态变量用于同步页面UI数据,分布式对象用于同步内存中的数据。
## 接口说明
迁移提供的能力如下,具体的API详见[接口文档](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-application-ability.md)
**表1** 应用迁移API接口功能介绍
|接口名 | 描述|
|:------ | :------|
| onContinue(wantParams : {[key: string]: any}): OnContinueResult | 迁移**发起端**在该回调中保存迁移所需要的数据,同时返回是否同意迁移:0表示同意,拒绝返回相应错误码。 |
| onCreate(want: Want,param:LaunchParam): void | 迁移**目标端**在该回调中完成数据恢复,并触发页面恢复。 |
| **enum** OnContinueResult | onContinue的返回值类型:AGREE表示同意;REJECT表示拒绝;MISMATCH表示版本不匹配 |
**图1** 迁移开发示意图
![continuation_dev](figures/continuation-info.png)
## 开发步骤
### 迁移应用
1. 配置
- 配置应用支持迁移
在module.json5中配置continuable字段:true表示支持迁移,false表示不支持,默认为false。配置为false的应用将被系统识别为无法迁移。
```javascript
"continuable": true
```
* 配置应用启动类型
迁移当前只支持多实例应用,需要在在module.json5中配置launchType字段为standard。
```javascript
"launchType": "standard"
```
* 申请分布式权限
支持跨端迁移的应用需要在module.json5申请分布式权限 DISTRIBUTED_DATASYNC。
```javascript
"requestPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
},
```
这个权限需要在应用首次启动的时候弹窗让用户授予,可以通过在ability的onWindowStageCreate中添加如下代码实现:
```javascript
requestPermissions = async () => {
let permissions: Array<string> = [
"ohos.permission.DISTRIBUTED_DATASYNC"
];
let needGrantPermission = false
let accessManger = accessControl.createAtManager()
Logger.info("app permission get bundle info")
let bundleInfo = await bundle.getApplicationInfo(BUNDLE_NAME, 0, 100)
Logger.info(`app permission query permission ${bundleInfo.accessTokenId.toString()}`)
for (const permission of permissions) {
Logger.info(`app permission query grant status ${permission}`)
try {
let grantStatus = await accessManger.verifyAccessToken(bundleInfo.accessTokenId, permission)
if (grantStatus === PERMISSION_REJECT) {
needGrantPermission = true
break;
}
} catch (err) {
Logger.error(`app permission query grant status error ${permission} ${JSON.stringify(err)}`)
needGrantPermission = true
break;
}
}
if (needGrantPermission) {
Logger.info("app permission needGrantPermission")
try {
await this.context.requestPermissionsFromUser(permissions)
} catch (err) {
Logger.error(`app permission ${JSON.stringify(err)}`)
}
} else {
Logger.info("app permission already granted")
}
}
```
2. 实现onContinue接口
onContinue接口在**发起端**被调用,主要用于在迁移发起时,通知开发者保存控件状态变量和内存中数据,准备迁移。当应用准备完成后,需要返回OnContinueResult.AGREE(0)表示同意迁移,否则返回相应的错误码拒绝迁移。如果不实现该接口,系统将默认为拒绝迁移。
导入模块
```javascript
import Ability from '@ohos.application.Ability';
import AbilityConstant from '@ohos.application.AbilityConstant';
```
- 要实现迁移,此接口必须实现并返回AGREE,否则默认为拒绝迁移。
- 示例
```javascript
onContinue(wantParam : {[key: string]: any}) {
Logger.info("onContinue using distributedObject")
// set user input data into want params
wantParam["input"] = AppStorage.Get<string>('ContinueInput');
Logger.info(`onContinue input = ${wantParam["input"]}`);
return AbilityConstant.OnContinueResult.AGREE
}
```
3. 在onCreate接口中实现迁移逻辑
onCreate接口在迁移**目标端**被调用,在目标端ability被拉起时,通知开发者同步已保存的内存数据和控件状态,完成后触发页面的恢复。如果不实现该接口中迁移相关逻辑,ability将会作为普通的启动方式拉起,无法恢复页面。
- 远端设备上,在onCreate中根据launchReason判断该次启动是否为迁移LaunchReason.CONTINUATION
- 完成数据恢复后,开发者需要调用**restoreWindowStage**来触发页面恢复。
* 示例
```javascript
onCreate(want, launchParam) {
Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
globalThis.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
let input = want.parameters.input // get user data from want params
AppStorage.SetOrCreate<string>('ContinueInput', input)
Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`)
this.contentStorage = new ContentStorage();
this.context.restoreWindowStage(this.contentStorage);
}
}
```
### 迁移数据
1. 使用分布式对象
分布式数据对象提供了与本地变量类似的操作,实现两个设备的数据同步,当设备1的应用A的分布式数据对象增、删、改数据后,设备2的应用A也可以获取到对应的数据变化,同时还能监听数据变更以及对端数据对象的上下线。用法详见[分布式对象指导文档](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/database/database-distributedobject-guidelines.md)
迁移场景中,分布式对象(distributedDataObject)主要用于将本机内存数据同步到目标设备。
- 发起端在onContinue中,将待迁移的数据存入分布式对象中,然后设置好session id,并通过wantParams将session id传到远端设备。
```javascript
import Ability from '@ohos.application.Ability';
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:undefined});
export default class MainAbility extends Ability {
contentStorage : ContenStorage
sessionId : string;
onContinue(wantParam : {[key: string]: any}) {
Logger.info("onContinue using distributedObject")
this.sessionId = distributedObject.genSessionId();
//set distributed data object session id
g_object.setSessionId(this.sessionId);
g_object.name = "Amy";
// set session id into want params
wantParam["session"] = this.sessionId;
return AbilityConstant.OnContinueResult.AGREE
}
```
- 目标设备在onCreate中,取出发起端传过来的session id,建立分布式对象并关联该session id,这样就能实现分布式对象的同步。需要注意的是,在调用restoreWindowStage之前,迁移需要的分布式对象必须全部关联完,保证能够获取到正确的数据。
```javascript
import Ability from '@ohos.application.Ability';
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:undefined});
export default class MainAbility extends Ability {
contentStorage : ContentStorage
sessionId : string;
statusCallback(sessionId, networkid, status) {
Logger.info(`continuation object status change, sessionId: ${sessionId}, status: ${status}, g_object.name: ${g_object.name}`)
}
onCreate(want, launchParam) {
Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
// get distributed data object session id from want params
this.sessionId = want.parameters.session
Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`)
g_object.on("status", this.statusCallback);
// set session id, so it will sync data from remote device
g_object.setSessionId(this.sessionId);
this.contentStorage = new ContentStorage();
this.context.restoreWindowStage(this.contentStorage);
}
}
}
```
以上完整的示例见sample
# Ability开发指导
## 场景介绍
Stage模型是基于API version 9的应用开发模型,对此模型的介绍详见[Stage模型综述](stage-brief.md)。基于Stage模型的Ability应用开发,主要涉及如下功能逻辑:
- 创建Page Ability应用,如视频播放、新闻资讯等,需要通过屏幕进行浏览的应用,以及支持人机交互。
- 获取Ability的配置信息,如ApplicationInfo、AbilityInfo及HapModuleInfo等。
- 启动/带参数启动/带返回结果启动/带AccountId启动其他Ability。
- 应用向用户申请授权。
- 系统环境变化通知给AbilityStage及Ability。
- 通用组件Call功能,详见[Call调用开发指导](stage-call.md)
- 连接ServiceAbility,与ServiceAbility断开连接,详见[ServiceExtensionAbility开发指导](stage-serviceextension.md)
- 应用迁移,详见[应用迁移开发指导](stage-ability-continuation.md)
## 接口说明
AbilityStage功能如下(AbilityStage类,拥有context属性,具体的API详见[接口文档](../reference/apis/js-apis-application-abilitystage.md)):
**表1** AbilityStage API接口功能介绍
|接口名|描述|
|:------|:------|
|void onCreate()|AbilityStage初始化时被调用。|
|string onAcceptWant(want: Want)|启动指定Ability时被调用。|
|void onConfigurationUpdated(config: Configuration)|全局配置发生变更时被调用。|
Ability功能如下(Ability类,具体的API详见[接口文档](../reference/apis/js-apis-application-ability.md)):
**表2** Ability API接口功能介绍
|接口名|描述|
|:------|:------|
|void onCreate(want: Want, param: AbilityConstant.LaunchParam)|Ability生命周期回调,Ability启动时被调用。|
|void onDestroy()|Ability生命周期回调,Ability销毁时被调用。|
|void onWindowStageCreate(windowStage: window.WindowStage)|Ability生命周期回调,创建window stage时被调用,应用开发者可通过window.WindowStage的接口执行页面加载等操作。|
|void onWindowStageDestroy()|Ability生命周期回调,销毁window stage时被调用。|
|void onForeground()|Ability生命周期回调,Ability切换至前台时被调用。|
|void onBackground()|Ability生命周期回调,Ability切换至后台时被调用。|
|void onNewWant(want: Want)|Ability回调,Ability的启动模式设置为单例时被调用。|
|void onConfigurationUpdated(config: Configuration)|Ability回调,Ability的系统配置更新时被调用。|
Ability类拥有context属性,context属性为AbilityContext类,AbilityContext类拥有abilityInfo、currentHapModuleInfo等属性,具体的API详见[接口文档](../reference/apis/js-apis-ability-context.md)
**表3** AbilityContext API接口功能介绍
|接口名|描述|
|:------|:------|
|void startAbility(want: Want, callback: AsyncCallback<void>)|启动Ability。|
|void startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>)|启动Ability。|
|void startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback<void>)|带AccountId启动Ability。|
|void startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback<void>)|带AccountId启动Ability。|
|void startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>)|带返回结果启动Ability。|
|void startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>)|带返回结果启动Ability。|
|void startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback<AbilityResult>)|带返回结果及AccountId启动Ability。|
|void startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback<void>)|带返回结果及AccountId启动Ability。|
|void terminateSelf(callback: AsyncCallback<void>)|销毁当前的Page Ability。|
|void terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>)|带返回结果销毁当前的Page Ability。|
## 开发步骤
### 创建Page Ability应用
创建Stage模型的Page Ability应用,需实现AbilityStage接口及Ability生命周期接口,并使用窗口提供的方法设置页面。具体示例代码如下:
1. 导入AbilityStage模块。
```
import AbilityStage from "@ohos.application.AbilityStage"
```
2. 实现AbilityStage接口。
```ts
export default class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("MyAbilityStage onCreate")
}
}
```
3. 导入Ability模块。
```js
import Ability from '@ohos.application.Ability'
```
4. 实现Ability生命周期接口。
`onWindowStageCreate(windowStage)`中通过loadContent接口设置应用要加载的页面,window接口的使用详见[窗口开发指导](../windowmanager/window-guidelines.md)
```ts
export default class MainAbility extends Ability {
onCreate(want, launchParam) {
console.log("MainAbility onCreate")
}
onDestroy() {
console.log("MainAbility onDestroy")
}
onWindowStageCreate(windowStage) {
console.log("MainAbility onWindowStageCreate")
windowStage.loadContent("pages/index").then((data) => {
console.log("MainAbility load content succeed with data: " + JSON.stringify(data))
}).catch((error) => {
console.error("MainAbility load content failed with error: "+ JSON.stringify(error))
})
}
onWindowStageDestroy() {
console.log("MainAbility onWindowStageDestroy")
}
onForeground() {
console.log("MainAbility onForeground")
}
onBackground() {
console.log("MainAbility onBackground")
}
}
```
### 获取AbilityStage及Ability的配置信息
AbilityStage类及Ability类均拥有context属性,应用可以通过`this.context`获取Ability实例的上下文,进而获取详细的配置信息。如下示例展示了AbilityStage通过context属性获取包代码路径、hap包名、ability名以及系统语言的方法。具体示例代码如下:
```ts
import AbilityStage from "@ohos.application.AbilityStage"
export default class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("MyAbilityStage onCreate")
let context = this.context
console.log("MyAbilityStage bundleCodeDir" + context.bundleCodeDir)
let currentHapModuleInfo = context.currentHapModuleInfo
console.log("MyAbilityStage hap module name" + currentHapModuleInfo.name)
console.log("MyAbilityStage hap module mainAbilityName" + currentHapModuleInfo.mainAbilityName)
let config = this.context.config
console.log("MyAbilityStage config language" + config.language)
}
}
```
如下示例展示了Ability通过context属性获取包代码路径、hap包名、ability名以及系统语言的方法。具体示例代码如下:
```ts
import Ability from '@ohos.application.Ability'
export default class MainAbility extends Ability {
onCreate(want, launchParam) {
console.log("MainAbility onCreate")
let context = this.context
console.log("MainAbility bundleCodeDir" + context.bundleCodeDir)
let abilityInfo = this.context.abilityInfo;
console.log("MainAbility ability bundleName" + abilityInfo.bundleName)
console.log("MainAbility ability name" + abilityInfo.name)
let config = this.context.config
console.log("MyAbilityStage config language" + config.language)
}
}
```
### 启动Ability
应用可以通过`this.context`获取Ability实例的上下文,进而使用AbilityContext中的StartAbility相关接口启动Ability。启动Ability可指定Want、StartOptions、accountId,通过callback形式或promise形式实现。具体示例代码如下:
```ts
let context = this.context
var want = {
"deviceId": "",
"bundleName": "com.example.MyApplication",
"abilityName": "MainAbility"
};
var options = {
windowMode: 0,
displayId: 2
};
context.startAbility(want, options).then((data) => {
console.log("Succeed to start ability with data: " + JSON.stringify(data))
}).catch((error) => {
console.error("Failed to start ability with error: "+ JSON.stringify(error))
})
```
### 跨设备启动Ability(当前仅对系统应用开放)
>说明:由于DeviceManager的getTrustedDeviceListSync接口仅对系统应用开放,当前跨设备启动Ability仅支持系统应用
跨设备场景下,需指定对端设备deviceId,具体示例代码如下:
```ts
let context = this.context
var want = {
"deviceId": getRemoteDeviceId(),
"bundleName": "com.example.MyApplication",
"abilityName": "MainAbility"
};
context.startAbility(want).then((data) => {
console.log("Succeed to start remote ability with data: " + JSON.stringify(data))
}).catch((error) => {
console.error("Failed to start remote ability with error: "+ JSON.stringify(error))
})
```
从DeviceManager获取指定设备的deviceId。具体示例代码如下:
```ts
import deviceManager from '@ohos.distributedHardware.deviceManager';
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");
return;
}
console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId);
return list[0].deviceId;
} else {
console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null");
}
}
```
### 应用向用户申请授权
应用需要某些权限如存储、位置信息、访问日历时,需要向用户申请授权。明确需要申请的权限后,在`module.json`中添加待申请的权限,同时通过接口`requestPermissionsFromUser`以动态弹窗的方式向用户申请授权。以访问日历为例,具体示例代码如下:
module.json的修改:
```json
"requestPermissions": [
{
"name": "ohos.permission.READ_CALENDAR"
}
]
```
通过动态弹窗向用户申请授权:
```ts
let context = this.context
let permissions: Array<string> = ['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))
})
```
在跨设备场景下,需要向用户申请数据同步的权限。具体示例代码如下:
```ts
let context = this.context
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC']
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))
})
```
### 系统环境变化通知给AbilityStage及Ability
全局配置,比如系统语言和颜色模式发生变化时,通过`onConfigurationUpdated`接口通知给AbilityStage和Ability。系统应用可以通过`updateConfiguration`接口更新系统语言和颜色模式。如下示例展示了AbilityStage的`onConfigurationUpdated`回调实现,系统语言和颜色模式发生变化时触发该回调。具体示例代码如下:
```ts
import Ability from '@ohos.application.Ability'
import ConfigurationConstant from '@ohos.application.ConfigurationConstant'
export default class MyAbilityStage extends AbilityStage {
onConfigurationUpdated(config) {
console.log("MyAbilityStage onConfigurationUpdated")
console.log("MyAbilityStage config language" + config.language)
console.log("MyAbilityStage config colorMode" + config.colorMode)
}
}
```
如下示例展示了Ability的`onConfigurationUpdated`回调实现,系统语言、颜色模式以及Display相关的参数,比如方向、Density,发生变化时触发该回调。具体示例代码如下:
```ts
import Ability from '@ohos.application.Ability'
import ConfigurationConstant from '@ohos.application.ConfigurationConstant'
export default class MainAbility extends Ability { {
onConfigurationUpdated(config) {
console.log("MainAbility onConfigurationUpdated")
console.log("MainAbility config language" + config.language)
console.log("MainAbility config colorMode" + config.colorMode)
console.log("MainAbility config direction" + config.direction)
console.log("MainAbility config screenDensity" + config.screenDensity)
console.log("MainAbility config displayId" + config.displayId)
}
}
```
## 开发实例
针对Stage模型Ability开发,有以下示例工程可供参考:
[eTSStageCallAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/eTSStageCallAbility)
本示例eTSStageCallAbility中,在Application目录的AbilityStage.ts中实现AbilityStage的接口,在MainAbility目录实现Ability的接口并设置"pages/index"为Ability的页面,在CalleeAbility目录实现另一个Ability并设置"pages/second"为Ability的页面。支持MainAbility启动CalleeAbility。
# Stage模型综述
### 设计思想
​ Stage模型的设计,主要是为了解决FA模型无法解决的开发场景问题,方便开发者更加方便地开发出分布式环境下的复杂应用。
​ Stage模型的设计思想如下图所示。
![stagedesign](figures/stagedesign.png)
​ Stage模型的设计基于如下三个出发点:
- **应用的能力与系统总体功能和功耗的平衡**
​ 在系统运行过程中,前台应用的资源占用会被优先保障,与此同时由于应用能力不同而产生的功耗,也需要符合系统整体功耗的要求。Stage模型通过Ability与UI分离、严格的后台管控、基于场景的服务机制及单进程模型来达成这种应用能力与整体系统功耗的平衡。
- **原生支持组件级的迁移和协同**
​ OpenHarmony是原生支持分布式的操作系统,应用框架需要从架构设计上使得组件更易于实现迁移和协同。Stage模型通过Ability与UI分离及UI展示与服务能力合一等模型特性,实现这一设计目标。
- **支持多设备和多窗口形态的特点**
​ 为了支持多种设备形态和更易于实现多种不同的窗口形态,需要组件管理服务和窗口管理服务在架构层面上是解耦的,从而方便裁剪,更有利于定制不同的窗口形态。Stage模型通过重新定义了Ability生命周期定义和设计组件管理服务和窗口管理服务的单项依赖解决这一问题。
### 基本概念
​ 下图展示了Stage模型中的基本概念。
![stageconcept](figures/stageconcept.png)
- **HAP**:即HarmonyAbilityPackage,OpenHarmony应用编译、分发、加载的基本单位,也称为module,每个HAP都有一个应用内唯一的名称,成为moduleName;
- **Bundle**:通过appid标识的OpenHarmony应用,Bundle可以包含多个HAP,每个应用都有一个bundleName,但是bundleName并不能唯一标识一个应用,appid中包含bundleName以及其他的更多信息,能够唯一标识一个应用;
- **AbilityStage**:对应HAP的运行期类,在HAP首次加载到进程中时创建,运行期开发者可见;
- **Application**:对应Bundle的运行期类,运行期开发者不可见;
- **Context**:提供运行期开发者可以调用的各种能力,Ability组件和各种ExtensionAbility都有各自不同的context类,他们都继承自基类Context,基类提供包名、moduleName、路径等信息;
- **Ability**:提供生命周期回调,持有AbilityContext,支持组件迁移/协同;
- **ExtensionAbility**:基于场景的服务扩展能力统称,系统定义了多种基于场景的ExtensionAbility类,它们持有各自的ExtensionAbilityContext;
- **WindowStage**:本地窗口管理器;
- **Window**:窗口 管理器管理的基本单元,持有一个ArkUI引擎实例;
- **Ark UI Page**:Ark声明式UI展示。
### 生命周期
​ Ability及AbilityStage的生命周期是应用的基本流程中最重要的概念。在[Ability框架概述](ability-brief.md)中,给出了FA模型与Stage模型的生命周期对比,这里重点对Ability生命周期切换以及和AbilityStage、WindowStage之间的调度关系进行介绍。
![stageabilitylifecyclecallback](figures/stageabilitylifecyclecallback.png)
​ 为了实现多设备形态上的裁剪和多窗口的可扩展性,OpenHarmony对组件管理和窗口管理进行了解耦。Stage模型定义Ability组件的生命周期,只包含创建、销毁、前后台等状态,而将与界面相关内容强相关的获焦、失焦状态放在WindowStage之中,从而实现Ability与窗口之间的弱耦合;在服务侧,窗口管理服务依赖于组件管理服务,前者通知后者前后台变化,这样组件管理服务仅感知前后台变化,不感知焦点变化。
### ExtensionAbility机制
​ 不同于用于页面展示的Ability,ExtensionAbility提供的是一种受限的服务运行环境。ExtensionAbility具有如下特点:
- 独立于主进程的单独进程运行,与主进程无IPC,共享一个存储沙箱;
- 独立的Context提供基于业务场景的api能力;
- 由系统触发创建,应用不能直接创建;
- ExtensionAbility和进程的生命周期受系统管理。
​ 下图以卡片服务使用场景为例进行展示,系统提供了FormExtensionAbility基类,开发者通过派生提供卡片的具体信息。FormExtensionAbility实例及其所在的ExtensionAbility进程的整个生命周期,都是由系统服务FormManagerService进行管理。
![ExtensionAbility](figures/ExtensionAbility.png)
### 进程模型
​ OpenHarmony系统中的应用均满足单进程模型。所谓的单进程模型,是指不允许应用配置多进程,应用中所有的进程都是由系统创建和管理的。每个应用至多并存三类进程:
- 主进程:运行所有的Ability组件、页面和业务逻辑;
- Extension进程:运行应用中的ExtensionAbility派生类,该进程由系统中的特定场景的服务管理其生命周期;
- Render进程:专门为webview创建的进程,用于加载webview的渲染库。
下图展示了应用的进程模型。
![stageprocessmodel](figures/stageprocessmodel.png)
此差异已折叠。
# ServiceExtensionAbility开发指导
## 场景介绍
ExtensionAbility,是Stage模型中新增的扩展组件的基类,一般用于处理无界面的任务,生命周期较简单,没有前后台生命周期。ServiceExtensionAbility是ExtensionAbility的扩展类。
开发者可以自定义类继承ServiceExtensionAbility,通过重写基类中相关生命周期方法,来做初始化、连接中、断开连接时相关业务逻辑操作。
## 接口说明
**表1** ServiceExtensionAbility中相关生命周期功能介绍
|接口名|描述|
|:------|:------|
|onCreate|首次调用startAbility、connectAbility时触发,开发者可以进行初始化操作。|
|onRequest|每次调用startAbility都会触发,首次调用时startId为1,重复调用startAbility递增。|
|onConnect|调用connectAbility触发,重复调用不会再次触发,除非调用disconnectAbility解除绑定后再调用;onConnect返回一个进程通信类RemoteObject。|
|onDisconnect|调用disconnectAbility触发,Extension如果是用connectAbility拉起的,并且已经没有其他应用绑定这个Extension,则会触发onDestroy生命周期销毁组件。|
|onDestroy|调用停止当前ability接口terminateSelf会触发。|
## 约束与限制
- OpenHarmony当前不支持三方应用创建ServiceExtensionAbility。
## 开发步骤
1.创建ServiceExtensionAbility
开发者在创建TS文件中自定义类继承ServiceExtensionAbility,重写基类回调函数,示例如下:
```js
import rpc from '@ohos.rpc'
class StubTest extends rpc.RemoteObject {
constructor(des) {
super(des);
}
onRemoteRequest(code, data, reply, option) {
}
}
class ServiceExt extends ServiceExtensionAbility {
onCreate(want) {
console.log('onCreate, want:' + want.abilityName);
}
onRequest(want, startId) {
console.log('onRequest, want:' + want.abilityName);
}
onConnect(want) {
console.log('onConnect , want:' + want.abilityName);
return new StubTest("test");
}
onDisconnect(want) {
console.log('onDisconnect, want:' + want.abilityName);
}
onDestroy() {
console.log('onDestroy');
}
}
```
2.注册ServiceExtensionAbility
需要在应用配置文件module.json中进行注册,注册类型type需要设置为service。
**module.json配置样例**
```json
"extensionAbilities":[{
"name": "ServiceExtAbility",
"icon": "$media:icon",
"description": "service",
"type": "service",
"visible": true,
"srcEntrance": "./ets/ServiceExtAbility/ServiceExtAbility.ts"
}]
```
## 开发实例
针对ServiceExtensionAbility开发,有以下示例工程可供参考:
- [ServiceExtensionAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/eTSServiceExtAbility)
本示例ServiceExtensionAbility中:
在ServiceExtensionAbility目录中的ServiceExtAbility.ts文件创建一个ServiceExtensionAbility实例。
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
首先,提供了支撑OpenHarmony应用的两个重要框架: 首先,提供了支撑OpenHarmony应用的两个重要框架:
- 应用程序的框架:[Ability开发](ability/ability-brief.md) - 应用程序的框架:[Ability开发](ability/fa-brief.md)
- UI的框架:[UI开发](ui/arkui-overview.md) - UI的框架:[UI开发](ui/arkui-overview.md)
所有应用都应该在这两个框架的基础之上进行功能的开发。 所有应用都应该在这两个框架的基础之上进行功能的开发。
......
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册