未验证 提交 0c73db63 编写于 作者: O openharmony_ci 提交者: Gitee

!21583 翻译完成:21224 task-management 精品内容上传

Merge pull request !21583 from wusongqing/TR21224
...@@ -19,8 +19,8 @@ ...@@ -19,8 +19,8 @@
- Cross-Application Data Sharing - Cross-Application Data Sharing
- [Data Sharing Overview](data-share-overview.md) - [Data Sharing Overview](data-share-overview.md)
- [Unified Data Definition](unified-data-definition.md) - [Unified Data Definition](unified-data-definition.md)
- One-to-Many Data Sharing (Only for System Applications) - One-to-Many Data Sharing (for System Applications Only)
- [Sharing Data Using DataShareExtensionAbility](share-data-by-datashareextensionability.md) - [Sharing Data Using DataShareExtensionAbility](share-data-by-datashareextensionability.md)
- [Silent Access via the DatamgrService](share-data-by-silent-access.md) - [Silent Access via the DatamgrService](share-data-by-silent-access.md)
- Many-to-Many Data Sharing - Many-to-Many Data Sharing
- [Sharing Data Using Unified Data Channels](unified-data-channels.md) - [Sharing Data Using Unified Data Channels](unified-data-channels.md)
\ No newline at end of file
...@@ -227,9 +227,9 @@ ...@@ -227,9 +227,9 @@
- [@ohos.distributedMissionManager (Distributed Mission Management)](js-apis-distributedMissionManager.md) - [@ohos.distributedMissionManager (Distributed Mission Management)](js-apis-distributedMissionManager.md)
- [@ohos.reminderAgentManager (Reminder Agent Management)](js-apis-reminderAgentManager.md) - [@ohos.reminderAgentManager (Reminder Agent Management)](js-apis-reminderAgentManager.md)
- [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](js-apis-resourceschedule-backgroundTaskManager.md) - [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](js-apis-resourceschedule-backgroundTaskManager.md)
- [@ohos.resourceschedule.workScheduler (Work Scheduler)](js-apis-resourceschedule-workScheduler.md) - [@ohos.resourceschedule.workScheduler (Deferred Task Scheduling)](js-apis-resourceschedule-workScheduler.md)
- [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](js-apis-resourceschedule-deviceUsageStatistics.md) - [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](js-apis-resourceschedule-deviceUsageStatistics.md)
- [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](js-apis-WorkSchedulerExtensionAbility.md) - [@ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks)](js-apis-WorkSchedulerExtensionAbility.md)
- application - application
- [WorkSchedulerExtensionContext](js-apis-inner-application-WorkSchedulerExtensionContext.md) - [WorkSchedulerExtensionContext](js-apis-inner-application-WorkSchedulerExtensionContext.md)
......
# @ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks) # @ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks)
The **WorkSchedulerExtensionAbility** module provides callbacks for Work Scheduler tasks. The **WorkSchedulerExtensionAbility** module provides callbacks for deferred task scheduling.
When developing an application, you can override the APIs of this module and add your own task logic to the APIs. When developing an application, you can override the APIs of this module and add your own task logic to the APIs.
...@@ -28,7 +28,7 @@ import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility' ...@@ -28,7 +28,7 @@ import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'
onWorkStart(work: workScheduler.WorkInfo): void onWorkStart(work: workScheduler.WorkInfo): void
Triggered when the Work Scheduler task starts. Called when the system starts scheduling the deferred task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -52,7 +52,7 @@ Triggered when the Work Scheduler task starts. ...@@ -52,7 +52,7 @@ Triggered when the Work Scheduler task starts.
onWorkStop(work: workScheduler.WorkInfo): void onWorkStop(work: workScheduler.WorkInfo): void
Triggered when the Work Scheduler task stops. Called when the system stops scheduling the deferred task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......
# WorkSchedulerExtensionContext # WorkSchedulerExtensionContext
The **WorkSchedulerExtensionContext** module, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md), is the context environment of the WorkSchedulerExtensionAbility. The **WorkSchedulerExtensionContext** module, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md), provides a context environment for the WorkSchedulerExtensionAbility.
This module provides APIs for accessing the resources of a WorkSchedulerExtensionAbility. This module provides APIs for accessing the resources of a WorkSchedulerExtensionAbility.
......
# @ohos.resourceschedule.workScheduler (Work Scheduler) # @ohos.resourceschedule.workScheduler (Deferred Task Scheduling)
The **workScheduler** module provides the APIs for registering, canceling, and querying Work Scheduler tasks, which do not have real-time constraints. The **workScheduler** module provides the APIs for registering, canceling, and querying deferred tasks.
The system executes Work Scheduler tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more. The system schedules and executes deferred tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more.
> **NOTE** > **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. > - 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.
> - The APIs of this module can be used only in the stage model. > - The APIs of this module can be used only in the stage model.
> - For details about the restrictions, see [Restrictions on Using Work Scheduler Tasks](../../task-management/background-task-overview.md#restrictions-on-using-work-scheduler-tasks).
## Modules to Import ## Modules to Import
...@@ -20,7 +19,7 @@ import workScheduler from '@ohos.resourceschedule.workScheduler'; ...@@ -20,7 +19,7 @@ import workScheduler from '@ohos.resourceschedule.workScheduler';
## workScheduler.startWork ## workScheduler.startWork
startWork(work: WorkInfo): void startWork(work: WorkInfo): void
Instructs the **WorkSchedulerService** to add the specified task to the execution queue. Instructs the WorkSchedulerService to add a task to the execution queue.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -71,7 +70,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -71,7 +70,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.stopWork ## workScheduler.stopWork
stopWork(work: WorkInfo, needCancel?: boolean): void stopWork(work: WorkInfo, needCancel?: boolean): void
Instructs the **WorkSchedulerService** to stop the specified task. Instructs the WorkSchedulerService to stop a task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -130,7 +129,7 @@ Obtains the latest task status. This API uses an asynchronous callback to return ...@@ -130,7 +129,7 @@ Obtains the latest task status. This API uses an asynchronous callback to return
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------- | | -------- | ------------------------------------- | ---- | ---------------------------------------- |
| workId | number | Yes | Task ID. | | 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; throws an exception otherwise.| | callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. If the specified task ID is valid, the task status obtained from the WorkSchedulerService is returned. Otherwise, an exception is thrown.|
**Error codes** **Error codes**
...@@ -178,7 +177,7 @@ Obtains the latest task status. This API uses a promise to return the result. ...@@ -178,7 +177,7 @@ Obtains the latest task status. This API uses a promise to return the result.
| Type | Description | | 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; throws an exception otherwise.| | Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. If the specified task ID is valid, the task status obtained from the WorkSchedulerService is returned. Otherwise, an exception is thrown.|
**Error codes** **Error codes**
...@@ -210,7 +209,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -210,7 +209,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.obtainAllWorks ## workScheduler.obtainAllWorks
obtainAllWorks(callback : AsyncCallback\<void>): Array\<WorkInfo> obtainAllWorks(callback : AsyncCallback\<void>): Array\<WorkInfo>
Obtains all tasks associated with this application. This API uses an asynchronous callback to return the result. Obtains all tasks associated with the application. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -218,13 +217,13 @@ Obtains all tasks associated with this application. This API uses an asynchronou ...@@ -218,13 +217,13 @@ Obtains all tasks associated with this application. This API uses an asynchronou
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ------------------------------- | | -------- | -------------------- | ---- | ------------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. All tasks associated with the current application.| | callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------- | --------------- | | ----------------------------- | --------------- |
| Array\<[WorkInfo](#workinfo)> | All tasks associated with the current application.| | Array\<[WorkInfo](#workinfo)> | All tasks associated with the application.|
**Error codes** **Error codes**
...@@ -255,7 +254,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -255,7 +254,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.obtainAllWorks ## workScheduler.obtainAllWorks
obtainAllWorks(): Promise\<Array\<WorkInfo>> obtainAllWorks(): Promise\<Array\<WorkInfo>>
Obtains all tasks associated with this application. This API uses a promise to return the result. Obtains all tasks associated with the application. This API uses a promise to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -263,7 +262,7 @@ Obtains all tasks associated with this application. This API uses a promise to r ...@@ -263,7 +262,7 @@ Obtains all tasks associated with this application. This API uses a promise to r
| Type | Description | | Type | Description |
| -------------------------------------- | ------------------------------ | | -------------------------------------- | ------------------------------ |
| Promise<Array\<[WorkInfo](#workinfo)>> | Promise used to return the result. All tasks associated with the current application.| | Promise<Array\<[WorkInfo](#workinfo)>> | Promise used to return all tasks associated with the application.|
**Error codes** **Error codes**
...@@ -292,7 +291,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -292,7 +291,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.stopAndClearWorks ## workScheduler.stopAndClearWorks
stopAndClearWorks(): void stopAndClearWorks(): void
Stops and cancels all tasks associated with the current application. Stops and cancels all tasks associated with the application.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -320,7 +319,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -320,7 +319,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.isLastWorkTimeOut ## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean 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. Checks whether the last execution of a task timed out. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -329,13 +328,13 @@ Checks whether the last execution of the specified task timed out. This API uses ...@@ -329,13 +328,13 @@ Checks whether the last execution of the specified task timed out. This API uses
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ---------------------------------------- | | -------- | -------------------- | ---- | ---------------------------------------- |
| workId | number | Yes | Task ID. | | workId | number | Yes | Task ID. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.| | callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ---------------------------------------- | | ------- | ---------------------------------------- |
| boolean | Callback used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.| | boolean | Returns **true** if the last execution of the task timed out; returns **false** otherwise.|
**Error codes** **Error codes**
...@@ -367,7 +366,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -367,7 +366,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.isLastWorkTimeOut ## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number): Promise\<boolean> 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. Checks whether the last execution of a task timed out. This API uses a promise to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -381,7 +380,7 @@ Checks whether the last execution of the specified task timed out. This API uses ...@@ -381,7 +380,7 @@ Checks whether the last execution of the specified task timed out. This API uses
| Type | Description | | 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.| | Promise\<boolean> | Promise used to return the result. If the last execution of the task timed out, **true** is returned. Otherwise, **false** is returned.|
**Error codes** **Error codes**
...@@ -411,15 +410,15 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -411,15 +410,15 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
``` ```
## WorkInfo ## WorkInfo
Provides detailed information about the task. For details about the constraints on configuring **WorkInfo**, see [Restrictions on Using Work Scheduler Tasks](../../task-management/background-task-overview.md#restrictions-on-using-work-scheduler-tasks). Provides detailed information about the task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------------- | --------------------------------- | ---- | ---------------- | | --------------- | --------------------------------- | ---- | ---------------- |
| workId | number | Yes | Task ID. | | workId | number | Yes | Task ID. |
| bundleName | string | Yes | Name of the Work Scheduler task bundle. | | bundleName | string | Yes | Bundle name of the application that requests the task. |
| abilityName | string | Yes | Name of the component to be notified by a Work Scheduler callback.| | abilityName | string | Yes | Name of the component to be notified by a deferred task scheduling callback. |
| networkType | [NetworkType](#networktype) | No | Network type. | | networkType | [NetworkType](#networktype) | No | Network type. |
| isCharging | boolean | No | Whether the device is charging. | | isCharging | boolean | No | Whether the device is charging. |
| chargerType | [ChargingType](#chargingtype) | No | Charging type. | | chargerType | [ChargingType](#chargingtype) | No | Charging type. |
...@@ -435,7 +434,7 @@ Provides detailed information about the task. For details about the constraints ...@@ -435,7 +434,7 @@ Provides detailed information about the task. For details about the constraints
| parameters | {[key: string]: number \| string \| boolean} | No | Carried parameters. | | parameters | {[key: string]: number \| string \| boolean} | No | Carried parameters. |
## NetworkType ## NetworkType
Enumerates the network types that can trigger the task. Enumerates the network types that can trigger task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -449,7 +448,7 @@ Enumerates the network types that can trigger the task. ...@@ -449,7 +448,7 @@ Enumerates the network types that can trigger the task.
| NETWORK_TYPE_ETHERNET | 5 | Ethernet. | | NETWORK_TYPE_ETHERNET | 5 | Ethernet. |
## ChargingType ## ChargingType
Enumerates the charging types that can trigger the task. Enumerates the charging types that can trigger task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -461,7 +460,7 @@ Enumerates the charging types that can trigger the task. ...@@ -461,7 +460,7 @@ Enumerates the charging types that can trigger the task.
| CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. | | CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. |
## BatteryStatus ## BatteryStatus
Enumerates the battery states that can trigger the task. Enumerates the battery states that can trigger task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -472,7 +471,7 @@ Enumerates the battery states that can trigger the task. ...@@ -472,7 +471,7 @@ Enumerates the battery states that can trigger the task.
| BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.| | BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.|
## StorageRequest ## StorageRequest
Enumerates the storage states that can trigger the task. Enumerates the storage states that can trigger task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......
# Background Task Management # Background Task Management
- Background Task - [Background Task Overview](background-task-overview.md)
- [Background Task Management Overview](background-task-overview.md) - [Transient Task](transient-task.md)
- [Transient Task Development](transient-task-dev-guide.md) - [Continuous Task](continuous-task.md)
- [Continuous Task Development](continuous-task-dev-guide.md) - [Deferred Task](work-scheduler.md)
- [Work Scheduler Development](work-scheduler-dev-guide.md) - [Agent-powered Reminder](agent-powered-reminder.md)
- [WorkSchedulerExtensionAbility Development](workscheduler-extensionability.md) - [Requesting Efficiency Resources (for Privileged System Applications Only)](efficiency-resource-request.md)
- [Efficiency Resource Request Development](efficiency-resources-apply-dev-guide.md)
- Agent-Powered Reminder
- [Agent-Powered Reminder Overview](reminder-agent-overview.md)
- [Agent-Powered Reminder Development](reminder-agent-development.md)
\ No newline at end of file
# Agent-Powered Reminder Development # Agent-powered Reminder
## Overview
### Introduction
After an application switches to the background or an application process is terminated, it may have scheduled tasks for reminding users, for example, flash sale reminders for shopping applications. To meet this requirement, the system provides agent-powered reminders (implemented by **reminderAgentManager**). When the application switches to the background or the process is terminated, the system sends reminders on behalf of the application. Currently, the following reminder types are supported: timer, calendar, and alarm.
- Timer: reminders based on countdown timers
- Calendar: reminders based on calendar events
- Alarm: reminders based on alarm clocks
### Constraints
- **Quantity limit**: A third-party application supports a maximum of 30 valid reminders. A system application supports a maximum of 10,000 valid reminders. The entire system supports a maximum of 12,000 valid reminders. (A reminder is considered valid as long as it is published.)
- **Redirection limit**: The application that is redirected to upon a click on the notification must be the application that requested the agent-powered reminder.
## Available APIs ## Available APIs
The agent-powered reminder feature provides APIs for publishing background reminders. You can call these APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. The APIs are encapsulated in the [reminderAgentManager](../reference/apis/js-apis-reminderAgentManager.md) class. The table below uses promise as an example to describe the APIs used for developing agent-powered reminders. For details about more APIs and their usage, see [reminderAgentManager](../reference/apis/js-apis-reminderAgentManager.md).
**Table 1** Major APIs in reminderAgentManager **Table 1** Main APIs for agent-powered reminders
| API | Description | | API| Description|
| ---------------------------------------- | ---------------------------------------- | | -------- | -------- |
| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback&lt;number&gt;): void<br>publishReminder(reminderReq: ReminderRequest): Promise&lt;number&gt; | Publishes a scheduled reminder.<br>The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application<br>and 2000 for the entire system.| | publishReminder(reminderReq: ReminderRequest): Promise&lt;number&gt; | Publishes a reminder.|
| cancelReminder(reminderId: number, callback: AsyncCallback&lt;void&gt;): void<br>cancelReminder(reminderId: number): Promise&lt;void&gt; | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)| | cancelReminder(reminderId: number): Promise&lt;void&gt; | Cancels a reminder.|
| getValidReminders(callback: AsyncCallback&lt;Array&lt;ReminderRequest&gt;&gt;): void<br>getValidReminders(): Promise&lt;Array&lt;ReminderRequest&gt;&gt; | Obtains all valid reminders set by the current application. | | getValidReminders(): Promise&lt;Array&lt;ReminderRequest&gt;&gt; | Obtains all valid reminders set by the current application.|
| cancelAllReminders(callback: AsyncCallback&lt;void&gt;): void<br>cancelAllReminders(): Promise&lt;void&gt; | Cancels all reminders set by the current application. | | cancelAllReminders(): Promise&lt;void&gt; | Cancels all reminders set by the current application.|
| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback&lt;void&gt;): void<br>addNotificationSlot(slot: NotificationSlot): Promise&lt;void&gt; | Registers a **NotificationSlot** instance to be used by the reminder. | | addNotificationSlot(slot: NotificationSlot): Promise&lt;void&gt; | Adds a notification slot.|
| removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback&lt;void&gt;): void<br>removeNotificationSlot(slotType: notification.SlotType): Promise&lt;void&gt; | Removes a **NotificationSlot** instance of a specified type. | | removeNotificationSlot(slotType: notification.SlotType): Promise&lt;void&gt; | Removes a notification slot.|
## How to Develop ## How to Develop
1. Request the **ohos.permission.PUBLISH_AGENT_REMINDER** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 1. Request the **ohos.permission.PUBLISH_AGENT_REMINDER** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. [Enable the notification feature](../notification/notification-enable.md). 2. [Enable the notification feature](../notification/notification-enable.md). Agent-powered reminders can be used only after being authorized by the user.
3. Import the modules. 3. Import the modules.
```js ```js
import reminderAgentManager from '@ohos.reminderAgentManager'; import reminderAgentManager from '@ohos.reminderAgentManager';
import notificationManager from '@ohos.notificationManager'; import notificationManager from '@ohos.notificationManager';
``` ```
4. Define a reminder agent. You can define the following types of reminder agents based on project requirements. 4. Define a reminder. You can define the following types of reminders based on project requirements.
- Countdown timer
- Timer
```js ```js
let targetReminderAgent: reminderAgentManager.ReminderRequestTimer = { let targetReminderAgent: reminderAgentManager.ReminderRequestTimer = {
reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, // The reminder type is countdown timer. reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, // The reminder type is timer.
triggerTimeInSeconds: 10, triggerTimeInSeconds: 10,
actionButton: [ // Set the button type and title displayed for the reminder in the notification panel. actionButton: [ // Set the button type and title displayed for the reminder in the notification panel.
{ {
...@@ -43,11 +62,11 @@ The agent-powered reminder feature provides APIs for publishing background remin ...@@ -43,11 +62,11 @@ The agent-powered reminder feature provides APIs for publishing background remin
type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE
} }
], ],
wantAgent: {// Information about the target UIAbility that is displayed after the reminder notification is touched. wantAgent: { // Information about the target UIAbility that is displayed after the reminder notification is touched.
pkgName: 'com.example.myapplication', pkgName: 'com.example.myapplication',
abilityName: 'EntryAbility' abilityName: 'EntryAbility'
}, },
maxScreenWantAgent: {// Information about the target ability that is automatically started when the specified reminder time arrives is displayed in full screen. maxScreenWantAgent: { // Information about the target UIAbility that is automatically started when the specified reminder time arrives is displayed in full screen.
pkgName: 'com.example.myapplication', pkgName: 'com.example.myapplication',
abilityName: 'EntryAbility' abilityName: 'EntryAbility'
}, },
...@@ -58,15 +77,16 @@ The agent-powered reminder feature provides APIs for publishing background remin ...@@ -58,15 +77,16 @@ The agent-powered reminder feature provides APIs for publishing background remin
slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder. slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder.
} }
``` ```
- Calendar event
- Calendar
```js ```js
let targetReminderAgent: reminderAgentManager.ReminderRequestCalendar = { let targetReminderAgent: reminderAgentManager.ReminderRequestCalendar = {
reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_CALENDAR, // The reminder type is calendar event. reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_CALENDAR, // The reminder type is calendar.
dateTime: { // Reminder time. dateTime: { // Reminder time.
year: 2023, year: 2023,
month: 7, month: 1,
day: 30, day: 1,
hour: 11, hour: 11,
minute: 14, minute: 14,
second: 30 second: 30
...@@ -83,17 +103,17 @@ The agent-powered reminder feature provides APIs for publishing background remin ...@@ -83,17 +103,17 @@ The agent-powered reminder feature provides APIs for publishing background remin
type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE
}, },
], ],
wantAgent: {// Information about the target UIAbility that is displayed after the reminder notification is touched. wantAgent: { // Information about the target UIAbility that is displayed after the reminder notification is touched.
pkgName: 'com.example.myapplication', pkgName: 'com.example.myapplication',
abilityName: 'EntryAbility' abilityName: 'EntryAbility'
}, },
maxScreenWantAgent: { // Information about the target UIAbility that is displayed after the reminder notification is touched. maxScreenWantAgent: { // Information about the target UIAbility that is automatically started when the specified reminder time arrives is displayed in full screen.
pkgName: 'com.example.myapplication', pkgName: 'com.example.myapplication',
abilityName: 'EntryAbility' abilityName: 'EntryAbility'
}, },
ringDuration: 5, // Ringing duration, in seconds. ringDuration: 5, // Ringing duration, in seconds.
snoozeTimes: 2, // Number of reminder snooze times. snoozeTimes: 2, // Number of reminder snooze times.
timeInterval: 300, // Reminder snooze interval, in seconds. timeInterval: 5, // Reminder snooze interval, in seconds.
title: 'this is title', // Reminder title. title: 'this is title', // Reminder title.
content: 'this is content', // Reminder content. content: 'this is content', // Reminder content.
expiredContent: 'this reminder has expired', // Content to be displayed after the reminder expires. expiredContent: 'this reminder has expired', // Content to be displayed after the reminder expires.
...@@ -102,11 +122,12 @@ The agent-powered reminder feature provides APIs for publishing background remin ...@@ -102,11 +122,12 @@ The agent-powered reminder feature provides APIs for publishing background remin
slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder. slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder.
} }
``` ```
- Alarm clock
- Alarm
```js ```js
let targetReminderAgent: reminderAgentManager.ReminderRequestAlarm = { let targetReminderAgent: reminderAgentManager.ReminderRequestAlarm = {
reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_ALARM, // The reminder type is alarm clock. reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_ALARM, // The reminder type is alarm.
hour: 23, // Hour portion of the reminder time. hour: 23, // Hour portion of the reminder time.
minute: 9, // Minute portion of the reminder time. minute: 9, // Minute portion of the reminder time.
daysOfWeek: [2], // Days of a week when the reminder repeats.. daysOfWeek: [2], // Days of a week when the reminder repeats..
...@@ -120,17 +141,17 @@ The agent-powered reminder feature provides APIs for publishing background remin ...@@ -120,17 +141,17 @@ The agent-powered reminder feature provides APIs for publishing background remin
type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE
}, },
], ],
wantAgent: {// Information about the target UIAbility that is displayed after the reminder notification is touched. wantAgent: { // Information about the target UIAbility that is displayed after the reminder notification is touched.
pkgName: 'com.example.myapplication', pkgName: 'com.example.myapplication',
abilityName: 'EntryAbility' abilityName: 'EntryAbility'
}, },
maxScreenWantAgent: { // Information about the target UIAbility that is displayed after the reminder notification is touched. maxScreenWantAgent: { // Information about the target UIAbility that is automatically started when the specified reminder time arrives is displayed in full screen.
pkgName: 'com.example.myapplication', pkgName: 'com.example.myapplication',
abilityName: 'EntryAbility' abilityName: 'EntryAbility'
}, },
ringDuration: 5, // Ringing duration, in seconds. ringDuration: 5, // Ringing duration, in seconds.
snoozeTimes: 2, // Number of reminder snooze times. snoozeTimes: 2, // Number of reminder snooze times.
timeInterval: 300, // Reminder snooze interval, in seconds. timeInterval: 5, // Reminder snooze interval, in seconds.
title: 'this is title', // Reminder title. title: 'this is title', // Reminder title.
content: 'this is content', // Reminder content. content: 'this is content', // Reminder content.
expiredContent: 'this reminder has expired', // Content to be displayed after the reminder expires. expiredContent: 'this reminder has expired', // Content to be displayed after the reminder expires.
...@@ -140,38 +161,33 @@ The agent-powered reminder feature provides APIs for publishing background remin ...@@ -140,38 +161,33 @@ The agent-powered reminder feature provides APIs for publishing background remin
} }
``` ```
5. Publish the reminder agent. After the agent is published, your application can use the agent-powered reminder feature. 5. Publish the reminder. After the reminder is published, your application can use the agent-powered reminder feature.
```js ```js
try { try {
reminderAgentManager.publishReminder(targetReminderAgent).then(res => { reminderAgentManager.publishReminder(targetReminderAgent).then(res => {
console.info('publishReminder promise reminderId: ' + res); console.info('Succeeded in publishing reminder. ');
let reminderId: number = res; let reminderId: number = res; // ID of the published reminder.
// ...
}).catch(err => { }).catch(err => {
console.info('publishReminder err code: ' + err.code + ' message:' + err.message); console.error(`Failed to publish reminder. Code: ${err.code}, message: ${err.message}`);
}) })
} catch (error) { } catch (err) {
console.info('publishReminder code: ' + error.code + ' message:' + error.message); console.error(`Failed to publish reminder. Code: ${err.code}, message: ${err.message}`);
} }
``` ```
The following figure shows the running effect of an alarm clock. 6. Delete the reminder as required.
![en-us_image_0000001416585578](figures/en-us_image_0000001416585578.png)
6. To delete a reminder task, call [reminderAgentManager.cancelReminder()](../reference/apis/js-apis-reminderAgentManager.md#reminderagentmanagercancelreminder).
```js
let reminderId = 0; // The reminderId is obtained from the callback after the agent is published.
```js
try { try {
// The reminder ID is obtained from the callback after the reminder is published.
reminderAgentManager.cancelReminder(reminderId).then(() => { reminderAgentManager.cancelReminder(reminderId).then(() => {
console.log("cancelReminder promise"); console.log('Succeeded in canceling reminder.');
}).catch(err => { }).catch(err => {
console.log("promise err code: " + err.code + ", message:" + err.message); console.error(`Failed to cancel reminder. Code: ${err.code}, message: ${err.message}`);
}); });
} catch (error) { } catch (err) {
console.log("cancelReminder code: " + error.code + ", message: " + error.message); console.error(`Failed to cancel reminder. Code: ${err.code}, message: ${err.message}`);
}; }
``` ```
# Background Task Management Overview # Background Task Overview
Frequent activities of background applications cause user devices to consume power quickly and respond slowly. To meet performance and power consumption requirements, the system allows applications in the background to execute only activities within the specifications. Activities beyond the specifications are suspended by default, and resources allocated to them will be reclaimed when the available resources are insufficient.
If an application or a service module running in the background has a service to continue, it can request a [transient task](#transient-tasks) to delay the suspension or a [continuous task](#continuous-tasks) to prevent the suspension. If an application needs to execute a non-real-time task when running in the background, it can request a [Work Scheduler task](#work-scheduler-tasks). A privileged application can also request [efficiency resources](#efficiency-resources) for more flexibility.
**Resource usage constraints**: The system provides resource quotas for running services, including the memory usage and CPU usage in a continuous period of time, as well as disk write I/O volume in 24 hours. When the quota is reached, the system generates a warning-level log if the process is running in the foreground, and terminates the process if it is running in the background. ## Introduction
When you return to the home screen, lock the screen, or switch to another application, the current application is switched to the background. If the application continues all the activities when running in the background, the power consumption of the device may be high and the UI may freeze. To reduce the power consumption and deliver a positive user experience, the system manages the application running in the background. For example, the system can suspend the application process by stopping allocating CPU resources. It can also stop distributing [common events](../application-models/common-event-overview.md) to the application process or terminate the process.
## Background Task Types - After an application is switched to the background for a short period of time (defined by the system), the system suspends the application process.
For more targeted management of background applications, OpenHarmony classifies background tasks into the following types and provides an extended resource request mode — efficiency resources:
- **No background task required**: An application or service module does not need further processing when switched to the background.
- **Transient task**: If an application or service module has an urgent, short task that must continue in the background until it is completed, such as data compression, the application or service module can request a transient task for delayed suspension.
- **Continuous task**: If an application or service module has a user-initiated, perceivable task that needs to run in an extended period of time in the background, it can request a continuous task so that it will not be suspended. Examples of continuous tasks include music playback, navigation, device connection, and VoIP.
- **Work Scheduler task**: The Work Scheduler provides a mechanism for applications to execute non-real-time tasks when the system is idle. If the preset conditions are met, the tasks will be placed in the execution queue and scheduled when the system is idle.
**Efficiency resources**: If an application needs to ensure that it will not be suspended within a period of time or can normally use certain system resources when it is suspended, it can request efficiency resources, including software and hardware resources. Different types of efficiency resources come with different privileges. For example, the CPU resources enable an application or process to keep running without being suspended, and the WORK_SCHEDULER resources allow for more task execution time before the application or process is suspended.
## Selecting a Background Task
![Background Task Selection](figures/bgtask_choice.png)
## Transient Tasks
As mentioned above, applications and service modules with transient tasks have their suspension delayed so that their running is not affected by background lifecycle management within the specified time frame.
> **NOTE**
>
> Applications and service modules can request transient tasks only for temporary tasks. The time quota is 3 minutes per time and 10 minutes per day. The system allocates the time frame based on the application scenario and system status.
### Restrictions on Using Transient Tasks
Adhere to the following constraints and rules when using transient tasks:
- **When to request**: An application can request a transient task only when it is running in the foreground or before it is suspended in the background. Otherwise, the application may be suspended, resulting in request failure. By default, an application has 6–12 seconds of running time (subject to the application scenario) before it is suspended in the background.
- **Timeout**: If a suspension delay is about to time out, the system notifies the application of the timeout by using a callback. The application must then cancel the delayed suspension. Otherwise, the application will be forcibly terminated.
- **When to cancel**: The application shall proactively cancel the request when the transient task is complete, rather than waiting for a system callback. Otherwise, the time frame allowed for the application to run in the background will be affected. - After an application running in the background is accessed for a short period of time (defined by the system), the system suspends the application process.
- **Quota mechanism**: To prevent abuse of the keepalive, each application has a certain quota every day (dynamically adjusted based on user habits). The default quota for a single day is 10 minutes, and the maximum quota for each request is 3 minutes. After using up the quota, an application cannot request transient tasks. Therefore, applications should cancel their request immediately after the transient tasks are complete, to avoid quota consumption. (Note: The quota refers to the requested duration and does not include the time when the application runs in the background.) - In case of resource insufficiency, the system terminates some application processes (by reclaiming all resources of these processes).
## Continuous Tasks To ensure the normal use of features such as music playback and calendar reminders in the background, the system provides constrained background tasks to extend the running time of applications in the background.
Continuous tasks provide background running lifecycle support for services that can be directly perceived by users and need to run in the background. For example, if a service needs to play audio or continue with navigation and positioning in the background, which can be perceived by users, it can execute a continuous task in the respective background mode. ## Background Task Types
### Background Mode Classification
OpenHarmony provides 9 background modes for services that require continuous task execution.
**Table 1** Background modes for continuous tasks
| Background Mode | Description | Hint in Notification Panel | Remarks |
| --------------------- | ------------------------- | ------------ | ------------------------- |
| dataTransfer | Data transfer through the network or peer device, such as download, backup, share, and transfer| A data transfer task is running. | - |
| audioPlayback | Audio output | An audio playback task is running. | - |
| audioRecording | Audio input | A recording task is running. | - |
| location | Positioning and navigation | A positioning task is running. | - |
| bluetoothInteraction | Bluetooth transmission | A Bluetooth-related task is running. | - |
| multiDeviceConnection | Multi-device application collaboration | A distributed task is running. | - |
| wifiInteraction | WLAN transmission | A WLAN-related task is running.| System API, which is available only to system applications|
| voip | Voice and video calls over VoIP | A call-related task is running. | System API, which is available only to system applications|
| taskKeeping | Computing task | A computing task is running | Effective only for specific devices |
### Restrictions on Using Continuous Tasks
- If a user triggers a perceivable task, such as broadcasting and navigation, the corresponding background mode is triggered. When the task is started, the system forcibly displays a notification to the user.
- If the task is complete, the application should exit the background mode. If the system detects that an application is not using the resources in the corresponding background mode when the application is running in the background, the application is suspended.
- Ensure that the requested continuous task background mode matches the application type. If the background mode does not match the application type, the system will suspend the task once it detects the issue.
- If a requested continuous task is not actually executed, the system will suspend the task once it detects the issue.
- An ability can request only one continuous task at a time. If an application has multiple abilities, you can request a continuous task for each ability.
## Work Scheduler Tasks
The Work Scheduler provides a mechanism for an application to execute a non-real-time task, for example, data learning, when the system is idle. The system places the Work Scheduler tasks requested by applications in a queue and determines the optimal scheduling time of each task based on the storage space, power consumption, temperature, and more. Persistence is supported. This means that a requested Work Scheduler task can be triggered when the application exits or the device restarts.
### Restrictions on Using Work Scheduler Tasks
The use of the Work Scheduler must comply with the following restrictions and rules:
- **Timeout**: The Work Scheduler callback can run only within the specified period of time. After the timeout, the callback automatically stops. The default timeout duration is 2 minutes. System applications can request [efficiency resources](efficiency-resources-apply-dev-guide.md) to obtain a longer duration (20 minutes in the charging state and 10 minutes in the non-charging state).
- **Execution frequency**: The system controls the execution frequency of Work Scheduler tasks based on the activity level of their respective applications. If an application has applied for the WORK_SCHEDULER resources through the efficiency resource API, the execution frequency is not limited within the validity period of the resources.
| Application Group | Work Scheduler Task Execution Frequency|
| ---------------------------------------- | ---------- |
| Active | At a minimum interval of 2 hours |
| Used every day | At a minimum interval of 4 hours |
| Frequently used | At a minimum interval of 24 hours |
| Infrequently used | At a minimum interval of 48 hours |
| Restricted | Prohibited |
| Unused | Prohibited |
| [Exemption group for efficiency resources](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#resourcetype)| Unlimited |
- **WorkInfo setting**
- **workId**, **bundleName**, and **abilityName** are mandatory. **bundleName** must be set to the name of the current application. Otherwise, the verification will fail.
- At least one condition must be set.
- The repeat interval must be at least 20 minutes and must work with the Always repeat pattern or repeat times. For standard-system devices, OpenHarmony provides the following types of constrained background tasks: transient tasks, continuous tasks, deferred tasks, agent-powered reminders, and efficiency resources.
- The carried parameters can be of the number, string, or boolean type. You can select a proper background task type to ensure that your application can continue running after switching to the background.
## Efficiency Resources - **Transient tasks**: suitable for tasks that have high requirements on real-time performance and can be completed in a short period of time, for example, status saving.
Efficiency resources are classified into software (WORK_SCHEDULER, COMMON_EVENT, and TIMER) and hardware resources (CPU, GPS, BLUETOOTH, and AUDIO). - **Continuous tasks**: suitable for tasks that need to run in the background for a long time and can be perceived by users, such as music playback in the background, navigation, and device connection. Using continuous tasks to prevent application processes from being suspended.
An application can perform different operations based on the requested efficiency resources. - **Deferred tasks**: suitable for tasks that do not have high requirements on real-time performance and can be executed at a later time. The system enqueues these tasks and schedules them in a unified manner based on the memory and power consumption.
* With the CPU resources, the application or process will not be suspended.
* With the WORK_SCHEDULER resources, the application has more time to execute a task and is not restricted by the execution frequency.
* With the COMMON_EVENT resources, the application can still receive common events when it is suspended in the background.
* With the TIMER resources, the application can use the timer to execute precise scheduled tasks.
* With the GPS, BLUETOOTH, and AUDIO resources, the application can still be woken up by related services to execute tasks when it is suspended in the background.
- **Agent-powered reminders**: After an application is switched to the background or an application process is terminated, the system sends a reminder on behalf of the application. You can create scheduled reminders for countdown timers, calendar events, and alarm clocks.
**Table 2** Efficiency resource types For system applications that provide basic capabilities, the system provides an API for [requesting energy resources](efficiency-resource-request.md). After an application calls the API, the system exempts the application from management.
| Name | Value | Description | **Figure 1** Selecting a type of background task
| -------------- | ---- | ------------------- | ![bgtask_choice](figures/bgtask_choice.png)
| CPU | 1 | CPU resources, which prevent the application from being suspended. |
| COMMON_EVENT | 2 | COMMON_EVENT resources, which prevent common events from being proxied when the application is suspended. |
| TIMER | 4 | TIMER resources, which prevent timers from being proxied when the application is suspended. |
| WORK_SCHEDULER | 8 | WORK_SCHEDULER resources, which ensure that the application has more time to execute the task. |
| BLUETOOTH | 16 | BLUETOOTH resources, which prevent Bluetooth resources from being proxied when the application is suspended. |
| GPS | 32 | GPS resources, which prevent GPS resources from being proxied when the application is suspended.|
| AUDIO | 64 | AUDIO resources, which prevent audio resources from being proxied when the application is suspended. |
### Restrictions on Using Efficiency Resources
- Applications or processes are responsible for requesting and releasing efficiency resources. A process can release the resources requested by itself, whereas an application can release the resources requested by both itself and its processes. For example, an application requests CPU resources, and its process requests CPU and WORK_SCHEDULER resources. If the application initiates CPU resource release, the CPU resources requested by the process are also released. However, the WORK_SCHEDULER resources are not released. If the process initiates CPU resource release, the CPU resources requested by the application are retained until being released by the application. > **NOTE**
- If persistent resources and non-persistent resources of the same type are requested, the persistent resources overwrite the non-persistent resources and they will not be released upon a timeout. For example, if an application first requests 10-second CPU resources and then requests persistent CPU resources at the 5th second, the CPU resources become persistent and will not be released at the tenth second. If the application releases the CPU resources at the 8th second, both types of CPU resources are released. >
- The WORK_SCHEDULER resources can be requested and released by applications, but not by processes. > 1. The system supports only constrained background tasks. If an application does not use a constrained background task or selects an inappropriate type of background task after switching to the background, its process will be suspended or terminated.
- To use efficiency resources, an application must be a system application that submits a request to the application center to configure the corresponding privileges. >
> 2. For an application that requests a constrained background task, only the priority of reclaiming the application process is increased. If system resources are severely insufficient, the application process may still be terminated.
# Continuous Task Development
## When to Use
If an application has a perceivable task that needs to run in an extended period of time in the background, it can request a continuous task so that it will not be suspended. Examples of continuous tasks include music playback, navigation, device connection, and VoIP.
There is no time limit for a continuous task running in the background. To prevent abuse, the system limits the number of continuous tasks that can be requested. It also attaches a notification to each of the tasks so that the tasks are perceivable. In addition, the system verifies whether the application is actually executing a continuous task.
## Available APIs
**Table 1** Main APIs for continuous tasks
| API | Description |
| ---------------------------------------- | ---------------------------- |
| startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise&lt;void&gt; | Requests a continuous task from the system so that the application keeps running in the background.|
| stopBackgroundRunning(context: Context): Promise&lt;void&gt; | Cancels the continuous task. |
For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md).
**Table 2** Background modes
| Name | Description | Item |
| ----------------------- | -------------- | --------------------- |
| DATA_TRANSFER | Data transfer. | dataTransfer |
| AUDIO_PLAYBACK | Audio playback. | audioPlayback |
| AUDIO_RECORDING | Audio recording. | audioRecording |
| LOCATION | Positioning and navigation. | location |
| BLUETOOTH_INTERACTION | Bluetooth-related task. | bluetoothInteraction |
| MULTI_DEVICE_CONNECTION | Multi-device connection. | multiDeviceConnection |
| WIFI_INTERACTION | WLAN-related task (reserved). | wifiInteraction |
| VOIP | Voice and video call (reserved). | voip |
| TASK_KEEPING | Computing task (for specific devices only).| taskKeeping |
## How to Develop
### Development in the Stage Model
For details about the stage model, see [Stage Model Development Overview](../application-models/stage-model-development-overview.md).
1. Configure the continuous task permission **ohos.permission.KEEP_BACKGROUND_RUNNING** in the **module.json5** file, and declare the corresponding background mode type for the ability that needs to use the task.
```
"module": {
"abilities": [
{
"backgroundModes": [
"dataTransfer",
"location"
], // Background mode
}
],
"requestPermissions": [
{
"name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission
}
]
}
```
2. If an application needs to execute a continuous task for its own, include the execution logic in the Page ability. This is because an application cannot use **startAbilityByCall** to create and run its own ability in the background due to the restriction of ability startup controls. For details, see [UIAbility Component Overview](../application-models/uiability-overview.md).
```ts
import wantAgent from '@ohos.app.ability.wantAgent';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
@Entry
@Component
struct Index {
@State message: string = 'test'
// Use getContext to obtain the context of the Page ability.
private context: any = getContext(this)
startContinuousTask() {
let wantAgentInfo = {
// List of operations to be executed after the notification is clicked.
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
}
],
// Type of the operation to perform after the notification is clicked.
operationType: wantAgent.OperationType.START_ABILITY,
// Custom request code.
requestCode: 0,
// Execution attribute of the operation to perform after the notification is clicked.
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
try {
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(this.context,
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation startBackgroundRunning failed Cause: " + err);
});
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
});
} catch (error) {
console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`);
}
}
stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(this.context).then(() => {
console.info("Operation stopBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation stopBackgroundRunning failed Cause: " + err);
});
} catch (error) {
console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
}
build() {
Row() {
Column() {
Text("Index")
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() { Text('Request continuous task').fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule)
.margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40)
.onClick(() => {
// Request a continuous task by clicking a button.
this.startContinuousTask();
// Execute the continuous task logic, for example, music playback.
})
Button() {Text('Cancel continuous task') .fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule)
.margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40)
.onClick(() => {
// Stop the continuous task.
// Cancel the continuous task by clicking a button.
this.stopContinuousTask();
})
}
.width('100%')
}
.height('100%')
}
}
```
3. If a continuous task needs to be executed in the background for another application or on another device, you can create and run an ability in the background in Call mode. For details, see [Using Ability Call (Intra-Device)](../application-models/uiability-intra-device-interaction.md#using-call-to-implement-uiability-interaction-for-system-applications-only) and [Using Ability Call (Inter-Device)](../application-models/hop-multi-device-collaboration.md#using-cross-device-call).
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import wantAgent from '@ohos.app.ability.wantAgent';
const MSG_SEND_METHOD: string = 'CallSendMsg';
let mContext = null;
function startContinuousTask() {
let wantAgentInfo = {
// List of operations to be executed after the notification is clicked.
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
}
],
// Type of the operation to perform after the notification is clicked.
operationType: wantAgent.OperationType.START_ABILITY,
// Custom request code.
requestCode: 0,
// Execution attribute of the operation to perform after the notification is clicked.
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
try {
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(mContext,
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((error) => {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
});
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
});
} catch (error) {
console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`);
}
}
function stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(mContext).then(() => {
console.info("Operation stopBackgroundRunning succeeded");
}).catch((error) => {
console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
});
} catch (error) {
console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
}
class MyParcelable {
num: number = 0;
str: String = "";
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageSequence) {
messageSequence.writeInt(this.num);
messageSequence.writeString(this.str);
return true;
}
unmarshalling(messageSequence) {
this.num = messageSequence.readInt();
this.str = messageSequence.readString();
return true;
}
}
function sendMsgCallback(data) {
console.info('BgTaskAbility funcCallBack is called ' + data)
let receivedData = new MyParcelable(0, "")
data.readParcelable(receivedData)
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`)
// You can execute different methods based on the str value in the sequenceable data sent by the caller.
if (receivedData.str === 'start_bgtask') {
startContinuousTask()
} else if (receivedData.str === 'stop_bgtask') {
stopContinuousTask();
}
return new MyParcelable(10, "Callee test");
}
export default class BgTaskAbility extends UIAbility {
onCreate(want, launchParam) {
console.info("[Demo] BgTaskAbility onCreate")
this.callee.on("test", sendMsgCallback);
try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback)
} catch (error) {
console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`)
}
mContext = this.context;
}
onDestroy() {
console.info("[Demo] BgTaskAbility onDestroy")
}
onWindowStageCreate(windowStage) {
console.info("[Demo] BgTaskAbility onWindowStageCreate")
windowStage.loadContent("pages/index").then((data)=> {
console.info(`load content succeed with data ${JSON.stringify(data)}`)
}).catch((error)=>{
console.error(`load content failed with error ${JSON.stringify(error)}`)
})
}
onWindowStageDestroy() {
console.info("[Demo] BgTaskAbility onWindowStageDestroy")
}
onForeground() {
console.info("[Demo] BgTaskAbility onForeground")
}
onBackground() {
console.info("[Demo] BgTaskAbility onBackground")
}
};
```
### Development in the FA Model
For details about how to use the ServiceAbility in the FA model, see [ServiceAbility Component Overview](../application-models/serviceability-overview.md).
If an application does not need to interact with a continuous task in the background, you can use **startAbility()** to start the ServiceAbility. In the **onStart** callback of the ServiceAbility, call **startBackgroundRunning()** to declare that the ServiceAbility needs to run in the background for a long time. After the task execution is complete, call **stopBackgroundRunning()** to release resources.
If an application needs to interact with a continuous task in the background (for example, an application related to music playback), you can use **connectAbility()** to start and connect to the ServiceAbility. After obtaining the proxy of the ServiceAbility, the application can communicate with the ServiceAbility and control the request and cancellation of continuous tasks.
1. Configure the continuous task permission **ohos.permission.KEEP_BACKGROUND_RUNNING** in the **config.json** file, and declare the corresponding background mode type for the ServiceAbility that needs to use the task.
```json
"module": {
"package": "com.example.myapplication",
"abilities": [
{
"backgroundModes": [
"dataTransfer",
"location"
], // Background mode
"type": "service" // The ability type is Service.
}
],
"reqPermissions": [
{
"name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission
}
]
}
```
2. Call the APIs for requesting and canceling a continuous task in the ServiceAbility.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.app.ability.wantAgent';
import rpc from "@ohos.rpc";
function startContinuousTask() {
let wantAgentInfo = {
// List of operations to be executed after the notification is clicked.
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
}
],
// Type of the operation to perform after the notification is clicked.
operationType: wantAgent.OperationType.START_ABILITY,
// Custom request code.
requestCode: 0,
// Execution attribute of the operation to perform after the notification is clicked.
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
try {
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation startBackgroundRunning failed Cause: " + err);
});
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
});
} catch (error) {
console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`);
}
}
function stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
console.info("Operation stopBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation stopBackgroundRunning failed Cause: " + err);
});
} catch (error) {
console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
}
async function processAsyncJobs() {
// Execute the continuous task.
// After the continuous task is complete, call the API to release resources.
stopContinuousTask();
}
let mMyStub;
class MyStub extends rpc.RemoteObject {
constructor(des) {
if (typeof des === 'string') {
super(des);
} else {
return null;
}
}
onRemoteRequest(code, data, reply, option) {
console.log('ServiceAbility onRemoteRequest called');
// The meaning of code is user-defined.
if (code === 1) {
// Receive the request code for requesting a continuous task.
startContinuousTask();
// Execute the continuous task.
} else if (code === 2) {
// Receive the request code for canceling the continuous task.
stopContinuousTask();
} else {
console.log('ServiceAbility unknown request code');
}
return true;
}
}
export default {
onStart() {
console.info('ServiceAbility onStart');
mMyStub = new MyStub("ServiceAbility-test");
// Call the API to start the task.
startContinuousTask();
processAsyncJobs();
},
onStop() {
console.info('ServiceAbility onStop');
},
onConnect(want) {
console.info('ServiceAbility onConnect');
return mMyStub;
},
onReconnect(want) {
console.info('ServiceAbility onReconnect');
},
onDisconnect() {
console.info('ServiceAbility onDisconnect');
},
onCommand(want, startId) {
console.info('ServiceAbility onCommand');
}
};
```
\ No newline at end of file
# Continuous Task
## Overview
### Introduction
If an application has a perceivable task that needs to run in an extended period of time in the background, it can request a continuous task to prevent itself from being suspended. Examples of continuous tasks include music playback and navigation in the background.
After an application requests a continuous task, the system verifies whether the application is actually executing the continuous task. It also attaches a notification to the continuous task. If the user deletes the notification, the system automatically stops the task.
### Use Cases
The table below lists the types of continuous tasks, which are used in various scenarios. You can select a task type suitable for your case based on the description.
**Table 1** Continuous task types
| Name| Description| Example Scenario|
| -------- | -------- | -------- |
| DATA_TRANSFER | Data transfer| The browser downloads a large file in the background.|
| AUDIO_PLAYBACK | Audio playback| A music application plays music in the background.|
| AUDIO_RECORDING | Audio recording| A recorder records audio in the background.|
| LOCATION | Positioning and navigation| A navigation application provides navigation in the background.|
| BLUETOOTH_INTERACTION | Bluetooth-related task| Transfer a file through Bluetooth.|
| MULTI_DEVICE_CONNECTION | Multi-device connection| Carry out distributed service connection.|
| WIFI_INTERACTION | WLAN-related task (for system applications only)| Transfer a file over Wi-Fi.|
| VOIP | Voice and video calls (for system applications only)| Use a system chat application to make an audio call in the background.|
| TASK_KEEPING | Computing task (for specific devices only)| Run antivirus software.|
- When an application requests a continuous task of the DATA_TRANSFER type, the system increases the priority of the application process to reduce the probability of terminating the process. However, it still suspends the process. To use the upload and download feature, the application must call the [upload and download agent API](../reference/apis/js-apis-request.md) so that the system functions as the agent.
- To implement background playback, the application must request an [AV session](../media/avsession-overview.md) in addition to a continuous task of the AUDIO_PLAYBACK type.
### Constraints
- **Ability limit**: In the stage model, only the UIAbility can request continuous tasks. In the FA model, only the ServiceAbility can request continuous tasks.
- **Quantity limit**: A UIAbility (ServiceAbility in the FA model) can request only one continuous task at a time. If a UIAbility has a running continuous task, it can request another one only after the running task is finished. If an application needs to request multiple continuous tasks at the same time, it must create multiple UIAbilities. After a UIAbility requests a continuous task, all the processes of the application are not suspended.
- **Running verification**: The system performs continuous task verification. If an application requests a continuous task but does not execute the task of the requested type or finishes the task, the system performs certain control. For example, if the system detects that an application has requested a continuous task of the AUDIO_PLAYBACK type but does not play audio, the system terminates the application process.
> **NOTE**
>
> The application shall proactively cancel a continuous task when it is finished. Otherwise, the system will forcibly cancel the task. For example, when a user taps the UI to pause music playback, the application must cancel the continuous task in a timely manner. When the user taps the UI again to continue music playback, the application needs to request a continuous task.
## Available APIs
The table below uses promise as an example to describe the APIs used for developing continuous tasks. For details about more APIs and their usage, see [Background Task Management](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md).
**Table 2** Main APIs for continuous tasks
| API| Description|
| -------- | -------- |
| startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md)): Promise&lt;void&gt; | Requests a continuous task.|
| stopBackgroundRunning(context: Context): Promise&lt;void&gt; | Cancels a continuous task.|
## How to Develop
### Stage Model
1. Request the **ohos.permission.KEEP_BACKGROUND_RUNNING** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Declare the continuous task type.
Declare the continuous task type for the target UIAbility in the **module.json5** file.
```ts
"module": {
"abilities": [
{
"backgroundModes": [
"audioRecording"
], // Background mode
}
],
...
}
```
3. Import the modules.
```ts
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import wantAgent from '@ohos.app.ability.wantAgent';
```
4. Request and cancel a continuous task.
- In the stage model, an application can request a continuous task for itself or another application either on the local device or on a remote device.
- When a continuous task is executed across devices or applications in the background, the UIAbility can be created and run in the background in call mode. For details, see [Using Call to Implement UIAbility Interaction (for System Applications Only)](../application-models/uiability-intra-device-interaction.md#using-call-to-implement-uiability-interaction-for-system-applications-only) and [Using Cross-Device Call](../application-models/hop-multi-device-collaboration.md#using-cross-device-call).
The code snippet below shows how an application requests a continuous task for itself.
```ts
@Entry
@Component
struct Index {
@State message: string = 'ContinuousTask';
// Use getContext to obtain the context of the UIAbility for the page.
private context = getContext(this);
startContinuousTask() {
let wantAgentInfo = {
// List of operations to be executed after the notification is clicked.
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility"
}
],
// Type of the operation to perform after the notification is clicked.
operationType: wantAgent.OperationType.START_ABILITY,
// Custom request code.
requestCode: 0,
// Execution attribute of the operation to perform after the notification is clicked.
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(this.context,
backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => {
console.info(`Succeeded in operationing startBackgroundRunning.`);
}).catch((err) => {
console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
});
} catch (error) {
console.error(`Failed to start background running. Code is ${error.code} message is ${error.message}`);
}
});
}
stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(this.context).then(() => {
console.info(`Succeeded in operationing stopBackgroundRunning.`);
}).catch((err) => {
console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
});
} catch (error) {
console.error(`Failed to stop background running. Code is ${error.code} message is ${error.message}`);
}
}
build() {
Row() {
Column() {
Text("Index")
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() {
Text('Request continuous task').fontSize(25).fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({ top: 10 })
.backgroundColor('#0D9FFB')
.width(250)
.height(40)
.onClick(() => {
// Request a continuous task by clicking a button.
this.startContinuousTask();
// Execute the continuous task logic, for example, music playback.
})
Button() {
Text ('Cancel continuous task').fontSize (25).fontWeight (FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({ top: 10 })
.backgroundColor('#0D9FFB')
.width(250)
.height(40)
.onClick(() => {
// Stop the continuous task.
// Cancel the continuous task by clicking a button.
this.stopContinuousTask();
})
}
.width('100%')
}
.height('100%')
}
}
```
The code snippet below shows how an application requests a continuous task across devices or applications.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
const MSG_SEND_METHOD: string = 'CallSendMsg'
let mContext = null;
function startContinuousTask() {
let wantAgentInfo = {
// List of operations to be executed after the notification is clicked.
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility",
}
],
// Type of the operation to perform after the notification is clicked.
operationType: wantAgent.OperationType.START_ABILITY,
// Custom request code.
requestCode: 0,
// Execution attribute of the operation to perform after the notification is clicked.
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(mContext,
backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => {
console.info(`Succeeded in operationing startBackgroundRunning.`);
}).catch((err) => {
console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
}
});
}
function stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(mContext).then(() => {
console.info(`Succeeded in operationing stopBackgroundRunning.`);
}).catch((err) => {
console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
}
}
class MyParcelable {
num: number = 0;
str: String = '';
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageSequence) {
messageSequence.writeInt(this.num);
messageSequence.writeString(this.str);
return true;
}
unmarshalling(messageSequence) {
this.num = messageSequence.readInt();
this.str = messageSequence.readString();
return true;
}
}
function sendMsgCallback(data) {
console.info('BgTaskAbility funcCallBack is called ' + data)
let receivedData = new MyParcelable(0, '')
data.readParcelable(receivedData)
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`)
// You can execute different methods based on the str value in the sequenceable data sent by the caller object.
if (receivedData.str === 'start_bgtask') {
startContinuousTask()
} else if (receivedData.str === 'stop_bgtask') {
stopContinuousTask();
}
return new MyParcelable(10, 'Callee test');
}
export default class BgTaskAbility extends UIAbility {
onCreate(want, launchParam) {
console.info("[Demo] BgTaskAbility onCreate")
this.callee.on('test', sendMsgCallback);
try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback)
} catch (error) {
console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`)
}
mContext = this.context;
}
onDestroy() {
console.info('[Demo] BgTaskAbility onDestroy')
}
onWindowStageCreate(windowStage) {
console.info('[Demo] BgTaskAbility onWindowStageCreate')
windowStage.loadContent("pages/index").then((data) => {
console.info(`load content succeed with data ${JSON.stringify(data)}`)
}).catch((error) => {
console.error(`load content failed with error ${JSON.stringify(error)}`)
})
}
onWindowStageDestroy() {
console.info('[Demo] BgTaskAbility onWindowStageDestroy')
}
onForeground() {
console.info('[Demo] BgTaskAbility onForeground')
}
onBackground() {
console.info('[Demo] BgTaskAbility onBackground')
}
};
```
### FA Model
1. Start and connect to a ServiceAbility.
- If no user interaction is required, use **startAbility()** to start the ServiceAbility. For details, see [ServiceAbility Component](../application-models/serviceability-overview.md). In the **onStart** callback of the ServiceAbility, call the APIs to request and cancel continuous tasks.
- If user interaction is required (for example, in music playback scenarios), use **connectAbility()** to start and connect to the ServiceAbility. For details, see [ServiceAbility Component](../application-models/serviceability-overview.md). After obtaining the agent of the ServiceAbility, the application can communicate with the ServiceAbility and control the request and cancellation of continuous tasks.
2. Configure permissions and declare the continuous task type.
Configure the **ohos.permission.KEEP_BACKGROUND_RUNNING** permission in the **config.json** file. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). In addition, declare the continuous task type for the ServiceAbility.
```js
"module": {
"package": "com.example.myapplication",
"abilities": [
{
"backgroundModes": [
"audioRecording",
], // Background mode
"type": "service" // The ability type is Service.
}
],
"reqPermissions": [
{
"name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission
}
]
}
```
3. Import the modules.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.app.ability.wantAgent';
import rpc from "@ohos.rpc";
```
4. Request and cancel a continuous task. In the ServiceAbility, call **startBackgroundRunning()** and **startBackgroundRunning()** to request and cancel a continuous task.
```js
function startContinuousTask() {
let wantAgentInfo = {
// List of operations to be executed after the notification is clicked.
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility"
}
],
// Type of the operation to perform after the notification is clicked.
operationType: wantAgent.OperationType.START_ABILITY,
// Custom request code.
requestCode: 0,
// Execution attribute of the operation to perform after the notification is clicked.
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => {
console.info(`Succeeded in operationing startBackgroundRunning.`);
}).catch((err) => {
console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
});
} catch (error) {
console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
}
});
}
function stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
console.info(`Succeeded in operationing stopBackgroundRunning.`);
}).catch((err) => {
console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
});
} catch (error) {
console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
}
}
async function processAsyncJobs() {
// Execute the continuous task.
// After the continuous task is complete, call the API to release resources.
stopContinuousTask();
}
let mMyStub;
class MyStub extends rpc.RemoteObject {
constructor(des) {
if (typeof des === 'string') {
super(des);
} else {
return null;
}
}
onRemoteRequest(code, data, reply, option) {
console.log('ServiceAbility onRemoteRequest called');
// Custom request code.
if (code === 1) {
// Receive the request code for requesting a continuous task.
startContinuousTask();
// Execute the continuous task.
} else if (code === 2) {
// Receive the request code for canceling the continuous task.
stopContinuousTask();
} else {
console.log('ServiceAbility unknown request code');
}
return true;
}
}
export default {
onStart(want) {
console.info('ServiceAbility onStart');
mMyStub = new MyStub("ServiceAbility-test");
// Call the API to start the task.
startContinuousTask();
processAsyncJobs();
},
onStop() {
console.info('ServiceAbility onStop');
},
onConnect(want) {
console.info('ServiceAbility onConnect');
return mMyStub;
},
onReconnect(want) {
console.info('ServiceAbility onReconnect');
},
onDisconnect() {
console.info('ServiceAbility onDisconnect');
},
onCommand(want, restart, startId) {
console.info('ServiceAbility onCommand');
}
};
```
# Requesting Efficiency Resources (for Privileged System Applications Only)
## Overview
### Introduction
Some system applications need to run for an extended period of time to provide basic system functions. For example, to maintain the connection between the system and server, the application that provides the default persistent connection push service must send heartbeat messages to the server at a short interval. To prevent the application process from being suspended, the application can request efficiency resources.
### Basic Concepts
- **APIs for requesting efficiency resources**: APIs used by a system application to request energy resources for its processes. An application or process can request CPU resources to prevent itself from being suspended.
- **Privileged system application**: a system application that is configured with the [runningResourcesApply privilege](../../device-dev/subsystems/subsys-app-privilege-config-guide.md#device-specific-application-privileges).
### Constraints
- Efficiency resources can be used only by privileged system applications.
- CPU resources can be requested by process or application. Other resources can be requested only by application.
## Available APIs
The table below lists the main APIs used for efficient resources. For details about more APIs and their usage, see [Background Task Management](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md).
**Table 1** Main APIs for efficiency resources
| API| Description|
| -------- | -------- |
| applyEfficiencyResources(request:EfficiencyResourcesRequest): void | Requests efficiency resources.|
| resetAllEfficiencyResources():void | Releases all efficiency resources.|
**Table 2** Parameters for requesting efficiency resources
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| resourceTypes | number | Yes| Type of the resource to request.|
| isApply | boolean | Yes| Whether the request is used to apply for resources.<br>- **true**: The request is used to apply for resources.<br>- **false**: The request is used to release resources.|
| timeOut | number | Yes| Duration for which the resource will be used, in milliseconds.|
| isPersist | boolean | No| Whether the resource is permanently held. The default value is **false**.<br>- **true**: The resource is permanently held.<br>- **false**: The resource is held for a limited period of time.|
| isProcess | boolean | No| Whether the request is initiated by a process. The default value is **false**.<br>- **true**: The request is initiated by a process.<br>- **false**: The request is initiated by an application.|
| reason | string | Yes| Reason for requesting the resource.|
**Table 3** Efficiency resource types
| Name| Value| Description|
| -------- | -------- | -------- |
| CPU | 1 | CPU resource. Such type of resource prevents an application from being suspended.|
| COMMON_EVENT | 2 | Common event resource. Such type of resource ensures that an application in the suspended state can receive common events.|
| TIMER | 4 | Timer resource. Such type of resource ensures that an application in the suspended state can be woken up by system timers.|
| WORK_SCHEDULER | 8 | Deferred task resource. Such type of resource provides a loose control policy for an application.|
| BLUETOOTH | 16 | Bluetooth resource. Such type of resource ensures that an application in the suspended state can be woken up by Bluetooth-related events.|
| GPS | 32 | GPS resource. Such type of resource ensures that an application in the suspended state can be woken up by GPS-related events.|
| AUDIO | 64 | Audio resource. Such type of resource prevents an application from being suspended when the application has an audio being played.|
## How to Develop
1. Import the module.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
```
2. Request efficiency resources.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
// The application needs to remain active in the background.
let request = {
resourceTypes: backgroundTaskManager.ResourceType.CPU, // The resource type is CPU, which prevents the application process from being suspended.
isApply: true, // The request is used to apply for the resources.
timeOut: 0, // Timeout interval. Resources are automatically released when the timeout interval expires.
reason: "apply", // Reason for the request.
isPersist: true, // The resources are permanently held.
isProcess: false, // The request is initiated by an application.
};
try {
backgroundTaskManager.applyEfficiencyResources(request);
console.info("Succeeded in invoking applyEfficiencyResources.");
} catch (error) {
console.error(`Failed to invoke applyEfficiencyResources. Code is ${error.code} message is ${error.message}`);
}
```
3. Release the efficiency resources. After completing work in the background, the application should release the resources in a timer manner. It can release some or all resources.
```js
// The application releases all the efficiency resources.
try {
backgroundTaskManager.resetAllEfficiencyResources();
} catch (error) {
console.error(`Failed to invoke resetAllEfficiencyResources. Code is ${error.code} message is ${error.message}`);
}
// The application releases some efficiency resources.
let request = {
resourceTypes: backgroundTaskManager.ResourceType.CPU,
isApply: false, // The request is used to release resources.
timeOut: 0,
reason: "apply",
isPersist: true,
isProcess: false, // The request is initiated by an application.
};
try {
backgroundTaskManager.applyEfficiencyResources(request);
console.info("Succeeded in invoking applyEfficiencyResources.");
} catch (error) {
console.error(`Failed to invoke applyEfficiencyResources. Code is ${error.code} message is ${error.message}`);
}
```
> **NOTE**
>
> Applications can dynamically request efficiency resources. Therefore, it is recommended that the application proactively releases the resources after the task is complete so as to reduce power consumption and ensure smooth user experience.
# Efficiency Resource Request Development
## When to Use
To further balance power consumption overhead of the system, privileged system applications can be suspended in the background as other applications. To ensure normal provisioning of important functions, efficiency resource APIs are provided for these applications so that they can execute special tasks and use specific system resources in the background. For example, if they want to receive common events when suspended, they can use the APIs to request the common event resources.
To upgrade your application as a privileged application, you must evaluate your service requirements and submit a request to the application center. The application center will determine whether to accept the request based on the conditions.
## Constraints
Only system applications can request efficiency resources.
## Available APIs
**Table 1** Main APIs for efficiency resources
| API | Description |
| ---------------------------------------- | ---------- |
| applyEfficiencyResources(request: [EfficiencyResourcesRequest](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#efficiencyresourcesrequest)): boolean | Requests efficiency resources. |
| resetAllEfficiencyResources():void | Releases efficiency resources.|
## How to Develop
1. When a privileged application in the background needs to use special resources, request the target resources from the system.
2. When the task is complete, release the resources in time. You can choose whether to release some or all resources.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
// Request efficiency resources.
let request = {
resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT |
backgroundTaskManager.ResourceType.TIMER,
isApply: true,
timeOut: 0,
reason: "apply",
isPersist: true,
isProcess: true,
};
let res;
try {
res = backgroundTaskManager.applyEfficiencyResources(request);
console.info("the result of request is: " + res);
} catch (error) {
console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`);
}
// Release some efficiency resources.
request = {
resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT,
isApply: false,
timeOut: 0,
reason: "reset",
isPersist: true,
isProcess: true,
};
try {
res = backgroundTaskManager.applyEfficiencyResources(request);
console.info("the result of request is: " + res);
} catch (error) {
console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`);
}
// Release all efficiency resources.
try {
backgroundTaskManager.resetAllEfficiencyResources();
} catch (error) {
console.error(`Operation resetAllEfficiencyResources failed. code is ${error.code} message is ${error.message}`);
}
```
\ No newline at end of file
# Agent-Powered Reminder Overview
To deliver a better user experience, OpenHarmony manages background application processes in a more orderly manner. Applications cannot reside in the background randomly, and their background behavior is strictly managed to minimize malicious behavior. However, for some applications that are running in the background or have exited, notifications may need to be sent at a specified time. For example, a shopping application wants to remind users of flash sale activities at some time points. To meet these service requirements, OpenHarmony provides the agent-powered redminder feature. After an application switches to the background or exits, their timing and pop-up notification functions are taken over by the background agent.
OpenHarmony provides the following types of background agents:
- Countdown timers: Applications can use this type to implement short-time timing notification services.
- Calendar events: Applications can use this type to implement long-time notification services.
- Alarm clocks: Applications can use this type to implement alarm-related services.
# Transient Task Development
## When to Use
By default, an application can run for a period of 6 to 12 seconds after it switches to the background. When this period expires, the application is suspended. If an application requires more time to execute an important task, it can call the **requestSuspendDelay** API to request a transient task to delay the suspension.
You are advised not to call the [requestSuspendDelay()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerrequestsuspenddelay) method to apply for delayed suspension after the application is running in the background. Instead, you need to call this interface to declare the execution time of the extended application to the system before performing any time-consuming operation. It is recommended that an application calls [requestSuspendDelay()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerrequestsuspenddelay) when it is running in the foreground, so as not to affect the transient task quota of the application.
An application can obtain the remaining duration before being suspended by calling [getRemainingDelayTime()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagergetremainingdelaytime). Each application has a daily time quota for transient tasks. Therefore, after the time-consuming task finishes execution, the application should call [cancelSuspendDelay()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagercancelsuspenddelay) to cancel the transient task in a timely manner.
Typical time-consuming tasks include saving status data to the local database, opening and processing a large file, and synchronizing data to the cloud server.
## Available APIs
**Table 1** Main APIs for transient tasks
| API | Description |
| ---------------------------------------- | ---------------------------------------- |
| requestSuspendDelay(reason: string, callback: Callback&lt;void&gt;): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo)| Requests delayed suspension after the application switches to the background.<br>The default duration of delayed suspension is 3 minutes when the battery level is normal and 1 minute when the battery level is low.|
| getRemainingDelayTime(requestId: number): Promise&lt;number&gt; | Obtains the remaining duration before the application is suspended.<br>This API uses a promise to return the result. |
| cancelSuspendDelay(requestId: number): void | Cancels the suspension delay. |
## How to Develop
When an application needs to execute a time-consuming task in the background, call the API to request a transient task. After the time-consuming task finishes execution, call the API to cancel the transient task.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
let id; // ID of the suspension delay request.
let delayTime; // Remaining duration for the suspension delay request.
// Request a suspension delay.
function requestSuspendDelay() {
let myReason = 'test requestSuspendDelay'; // Reason for the suspension delay request.
try {
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
// The callback is invoked to notify the application that the suspension delay request is about to time out. The application needs to perform some cleanup and annotation operations and cancels the transient task.
console.info("[backgroundTaskManager] Request suspension delay will time out.");
backgroundTaskManager.cancelSuspendDelay(id);
})
id = delayInfo.requestId;
delayTime = delayInfo.actualDelayTime;
console.info("[backgroundTaskManager] The requestId is: " + id);
console.info("[backgroundTaskManager]The actualDelayTime is: " + delayTime);
} catch (error) {
console.error(`[backgroundTaskManager] requestSuspendDelay failed. code is ${error.code} message is ${error.message}`);
}
}
// Obtain the remaining duration before the application is suspended.
async function getRemainingDelayTime() {
try {
await backgroundTaskManager.getRemainingDelayTime(id).then(res => {
console.log('[backgroundTaskManager] promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
}).catch(error => {
console.error(`[backgroundTaskManager] promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`);
})
} catch (error) {
console.error(`[backgroundTaskManager] promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`);
}
}
// Cancel the suspension delay.
function cancelSuspendDelay() {
backgroundTaskManager.cancelSuspendDelay(id);
}
async function performingLongRunningTask() {
// Before executing a time-consuming task, call the API to request a transient task to delay the suspension.
requestSuspendDelay();
// If required, obtain the available time quota through the getRemainingDelayTime() API.
await getRemainingDelayTime();
if (delayTime < 0) {// If the time is less than a certain value, cancel the time-consuming task.
// Handle the scenario where the time quota is insufficient.
cancelSuspendDelay();
return;
}
// Execute the time-consuming task.
// After the time-consuming task is executed, call the API to cancel the transient task.
cancelSuspendDelay();
}
```
# Transient Task
## Overview
An application is suspended after it runs in the background for a short period of time. If the application needs to execute a short-time task in the background, for example, saving the status, it can request a transient task to extend the running time in the background.
### Constraints
- **When to request**: An application can request a transient task when it is running in the foreground or within 5 seconds after it switches to the background.
- **Quantity limit**: An application can request a maximum of three transient tasks during a time segment. As shown in the figure below, the application requests two transient tasks in the time segments ①, ②, and ③, and one transient task in the time segment ④.
- **Quota mechanism**: An application has a certain quota for transient tasks (adjusted based on the system status and user habits). The default quota for a single day (within 24 hours) is 10 minutes, and the maximum quota for each request is 3 minutes. In case of [low battery](../reference/apis/js-apis-battery-info.md), the default quota for each request is 1 minute. After the quota is used up, the application cannot request transient tasks anymore. The system also provides an API for an application to query the remaining duration of a transient task so as to determine whether to continue running other services.
- **Quota calculation**: Transient tasks are timed only when the application is running in the background. If the application has multiple transient tasks during the same time segment, no repeated timing is performed. As in the figure below, the application has two transient tasks, A and B. Task A is requested when the application is running in the foreground, and the timing starts when the application switches to the background (marked as ①). When the application switches to the foreground, the timing stops (marked as ②). When the application switches to the background again, the timing starts again (marked as ③). When task A is finished, task B still exists, and therefore the timing continues (marked as ④). In this process, the total time consumed by the transient tasks is ①+③+④.
**Figure 1** Quota calculation for transient tasks
![transient-task](figures/transient-task.png)
> **NOTE**
>
> The application shall proactively cancel a transient task when it is finished. Otherwise, the time frame allowed for the application to run in the background will be affected.
- **Timeout**: If a transient task is about to time out, the system notifies the application of the timeout by using a callback. The application needs to cancel the task. Otherwise, the system forcibly terminates the application process.
## Available APIs
The table below lists the main APIs used for transient task development. For details about more APIs and their usage, see [Background Task Management](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md).
**Table 1** Main APIs for transient tasks
| API| Description|
| -------- | -------- |
| requestSuspendDelay(reason: string, callback: Callback&lt;void&gt;): DelaySuspendInfo | Requests a transient task.|
| getRemainingDelayTime(requestId: number): Promise&lt;number&gt; | Obtains the remaining time of a transient task.|
| cancelSuspendDelay(requestId: number): void | Cancels a transient task.|
## How to Develop
1. Import the module.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
```
2. Request a transient task and implement the callback.
```js
let id; // ID of the transient task.
let delayTime; // Remaining time of the transient task.
// Request a transient task.
function requestSuspendDelay() {
let myReason = 'test requestSuspendDelay'; // Reason for the request.
try {
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
// Callback function, which is triggered when the transient task is about to time out. The application can carry out data clear and annotation, and cancel the task in the callback.
console.info('Succeeded in requesting suspend delay.');
backgroundTaskManager.cancelSuspendDelay(id);
})
id = delayInfo.requestId;
delayTime = delayInfo.actualDelayTime;
} catch (err) {
console.error(`Failed to request suspend delay. Code: ${err.code}, message: ${err.message}`);
}
}
```
3. Obtain the remaining time of the transient task. Based on the remaining time, the application determines whether to continue to run other services. For example, the application has two small tasks. After the first task is executed, it queries the remaining time of the current transient task to determine whether to execute the second task.
```js
async function getRemainingDelayTime() {
try {
backgroundTaskManager.getRemainingDelayTime(id).then(res => {
console.info('Succeeded in getting remaining delay time.');
}).catch(err => {
console.error(`Failed to get remaining delay time. Code: ${err.code}, message: ${err.message}`);
})
} catch (err) {
console.error(`Failed to get remaining delay time. Code: ${err.code}, message: ${err.message}`);
}
}
```
4. Cancel the transient task.
```js
function cancelSuspendDelay() {
backgroundTaskManager.cancelSuspendDelay(id);
}
```
# Work Scheduler Development
## When to Use
If your application needs to execute a non-real-time task or a persistent task, for example, data learning, you can harness the Work Scheduler mechanism, which will schedule the task based on the storage space, power consumption, temperature, and more when the preset conditions are met. Your application must implement the callbacks provided by [WorkSchedulerExtensionAbility](./workscheduler-extensionability.md) for Work Scheduler tasks.
For details about the restrictions, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
## Available APIs
**Table 1** Major workScheduler APIs
API | Description
---------------------------------------------------------|-----------------------------------------
startWork(work: WorkInfo): void; | Starts a Work Scheduler task.
stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops a Work Scheduler task.
getWorkStatus(workId: number, callback: AsyncCallback\<WorkInfo>): void;| Obtains the status of a Work Scheduler task. This API uses an asynchronous callback to return the result.
getWorkStatus(workId: number): Promise\<WorkInfo>; | Obtains the status of a Work Scheduler task. This API uses a promise to return the result.
obtainAllWorks(callback: AsyncCallback\<void>): Array\<WorkInfo>;| Obtains all the Work Scheduler tasks. This API uses an asynchronous callback to return the result.
obtainAllWorks(): Promise<Array\<WorkInfo>>;| Obtains all the Work Scheduler tasks. This API uses a promise to return the result.
stopAndClearWorks(): void;| Stops and clears all the Work Scheduler tasks.
isLastWorkTimeOut(workId: number, callback: AsyncCallback\<void>): boolean;| Checks whether the last execution of the specified task has timed out. This API uses an asynchronous callback to return the result. It is applicable to repeated tasks.
isLastWorkTimeOut(workId: number): Promise\<boolean>;| Checks whether the last execution of the specified task has timed out. This API uses a promise to return the result. It is applicable to repeated tasks.
**Table 2** WorkInfo parameters
For details about the restriction on configuring **WorkInfo**, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
Name| Type|Description
---------------------------------------------------------|-----------------------------------------|---------------------------------------------------------
workId| number | ID of the Work Scheduler task. Mandatory.
bundleName| string | Bundle name of the Work Scheduler task. Mandatory.
abilityName| string | Name of the ability to be notified by a Work Scheduler callback. Mandatory.
networkType | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | Network type.
isCharging| boolean | Whether the device is charging.
chargerType| [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | Charging type.
batteryLevel| number | Battery level.
batteryStatus| [BatteryStatus](../reference/apis/js-apis-resourceschedule-workScheduler.md#batterystatus) | Battery status.
storageRequest| [StorageRequest](../reference/apis/js-apis-resourceschedule-workScheduler.md#storagerequest) |Storage status.
isRepeat| boolean |Whether the task is repeated.
repeatCycleTime| number |Repeat interval.
repeatCount | number|Number of repeat times.
parameters | {[key: string]: number | string | boolean} |Carried parameters.
**Table 3** Work Scheduler callbacks
API | Description
---------------------------------------------------------|-----------------------------------------
onWorkStart(work: WorkInfo): void | Called when the Work Scheduler task starts.
onWorkStop(work: WorkInfo): void | Called when the Work Scheduler task stops.
### How to Develop
1. Import the modules.
Import the **workScheduler** module.
```js
import workScheduler from '@ohos.resourceschedule.workScheduler';
```
Import the **WorkSchedulerExtensionAbility** module.
```js
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
```
2. Develop an ExtensionAbility to execute a Work Scheduler task. For details about the ExtensionAbility, see [ExtensionAbility Component Overview](../application-models/extensionability-overview.md) and [WorkSchedulerExtensionAbility Development](./workscheduler-extensionability.md).
```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
export default class MyExtension extends WorkSchedulerExtensionAbility {
onWorkStart(workInfo) {
console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo));
}
onWorkStop(workInfo) {
console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo));
}
}
```
3. Start a Work Scheduler task.
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler';
let workInfo = {
workId: 1,
batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
isRepeat: false,
isPersisted: true,
bundleName: "com.example.myapplication",
abilityName: "MyExtension",
parameters: {
mykey0: 1,
mykey1: "string value",
mykey2: true,
mykey3: 1.5
}
}
try{
workScheduler.startWork(workInfo);
console.info('workschedulerLog startWork success');
} catch (error) {
console.error(`workschedulerLog startwork failed. code is ${error.code} message is ${error.message}`);
}
```
4. Stop the Work Scheduler task.
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler';
let workInfo = {
workId: 1,
batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
isRepeat: false,
isPersisted: true,
bundleName: "com.example.myapplication",
abilityName: "MyExtension",
parameters: {
mykey0: 1,
mykey1: "string value",
mykey2: true,
mykey3: 1.5
}
}
try{
workScheduler.stopWork(workInfo, false);
console.info('workschedulerLog stopWork success');
} catch (error) {
console.error(`workschedulerLog stopWork failed. code is ${error.code} message is ${error.message}`);
}
```
5. Obtain a specified Work Scheduler task.
```ts
try{
workScheduler.getWorkStatus(50, (error, res) => {
if (error) {
console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
} else {
for (let item in res) {
console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`);
}
}
});
} catch (error) {
console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
}
```
6. Obtain all the Work Scheduler tasks.
```ts
try{
workScheduler.obtainAllWorks((error, res) =>{
if (error) {
console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`);
} else {
console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`);
}
});
} catch (error) {
console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`);
}
```
7. Stop and clear all the Work Scheduler tasks.
```ts
try{
workScheduler.stopAndClearWorks();
console.info(`workschedulerLog stopAndClearWorks success`);
} catch (error) {
console.error(`workschedulerLog stopAndClearWorks failed. code is ${error.code} message is ${error.message}`);
}
```
8. Check whether the last execution of a specified Work Scheduler task has timed out.
```ts
try{
workScheduler.isLastWorkTimeOut(500, (error, res) =>{
if (error) {
console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`);
} else {
console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`);
}
});
} catch (error) {
console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`);
}
```
\ No newline at end of file
# Deferred Task
## Overview
### Introduction
If an application needs to execute a non-real-time task after switching to the background, for example, if the application wants to obtain emails irregularly when the network is available, the application can request deferred tasks. When the specified conditions (including the network type, charging type, storage status, battery status, and timing status) are met, the system adds the task to the execution queue. Then the system starts the application to execute the task based on the memory, power consumption, device temperature, and user habits.
### Working Principle
**Figure 1** Working principle of deferred task scheduling
![WorkScheduler](figures/WorkScheduler.png)
An application calls the **WorkScheduler** APIs to register, delete, and query deferred tasks. Based on the task-specific conditions (specified by **WorkInfo**, including the network type, charging type, and storage status) and system status (including the memory, power consumption, device temperature, and user habits), the WorkSchedulerService determines the time to schedule the tasks.
When the scheduling conditions are met or the task scheduling ends, the system calls back **onWorkStart()** or **onWorkStop()** in [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md). The system also creates an independent process for the **WorkSchedulerExtensionAbility** and provides a duration for the **WorkSchedulerExtensionAbility** to run. You can implement your own service logic in the callback functions.
### Constraints
- **Quantity limit**: An application can request a maximum of 10 deferred tasks during a time segment.
- **Execution frequency limit**: The system controls the execution frequency of deferred tasks based on the [application activity group](../reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md). Applications that request the WORK_SCHEDULER resource are placed in the efficiency resource exemption group.
**Table 1** Application activity groups
| Group| Deferred Task Execution Frequency|
| -------- | -------- |
| Group of active applications| At a minimum interval of 2 hours|
| Group of frequently used applications| At a minimum interval of 4 hours|
| Group of applications that are used neither frequently nor rarely| At a minimum interval of 24 hours|
| Group of rarely used applications| At a minimum interval of 48 hours|
| Group of restricted applications| Forbidden|
| Group of applications never used| Forbidden|
| Efficiency resource exemption group| No restriction|
- **Timeout**: The WorkSchedulerExtensionAbility can run for a maximum of 2 minutes for a single callback. If the application does not cancel the deferred task upon a timeout, the system forcibly terminates the process for the WorkSchedulerExtensionAbility. Privileged system applications can request the WORK_SCHEDULER resource to extend the duration to 20 minutes in the charging state and 10 minutes in the non-charging state.
- **Scheduling delay**: The system schedules deferred tasks in a unified manner based on the memory, power consumption, device temperature, and user habits. For example, when the system memory resources are insufficient or the temperature reaches a certain level, the system delays task scheduling.
- **Restrictions for WorkSchedulerExtensionAbility**: The following APIs cannot be called in the WorkSchedulerExtensionAbility:
[@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md)
[@ohos.backgroundTaskManager (Background Task Management)](../reference/apis/js-apis-backgroundTaskManager.md)
[@ohos.multimedia.camera (Camera Management)](../reference/apis/js-apis-camera.md)
[@ohos.multimedia.audio (Audio Management)](../reference/apis/js-apis-audio.md)
[@ohos.multimedia.media (Media)](../reference/apis/js-apis-media.md)
## Available APIs
The table below lists the APIs used for developing deferred tasks. For details about more APIs and their usage, see [@ohos.resourceschedule.workScheduler (Deferred Task Scheduling)](../reference/apis/js-apis-resourceschedule-workScheduler.md).
**Table 2** Main APIs for deferred tasks
| API| Description|
| -------- | -------- |
| startWork(work: WorkInfo): void; | Starts a deferred task.|
| stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops a deferred task.|
| getWorkStatus(workId: number, callback: AsyncCallback&lt;WorkInfo&gt;): void; | Obtains the status of a deferred task. This API uses an asynchronous callback to return the result.|
| getWorkStatus(workId: number): Promise&lt;WorkInfo&gt;; | Obtains the status of a deferred task. This API uses a promise to return the result.|
| obtainAllWorks(callback: AsyncCallback&lt;void&gt;): Array&lt;WorkInfo&gt;; | Obtains all the deferred tasks. This API uses an asynchronous callback to return the result.|
| obtainAllWorks(): Promise&lt;Array&lt;WorkInfo&gt;&gt;; | Obtains all the deferred tasks. This API uses a promise to return the result.|
| stopAndClearWorks(): void; | Stops and clears all the deferred tasks.|
| isLastWorkTimeOut(workId: number, callback: AsyncCallback&lt;void&gt;): boolean; | Checks whether the last execution of a deferred task has timed out. This API uses an asynchronous callback to return the result. It is applicable to repeated tasks.|
| isLastWorkTimeOut(workId: number): Promise&lt;boolean&gt;; | Checks whether the last execution of a deferred task has timed out. This API uses a promise to return the result. It is applicable to repeated tasks.|
**Table 3** Options of WorkInfo
| Name| Type| Description.|
| -------- | -------- | -------- |
| workId | number | ID of a deferred task. This parameter is mandatory.|
| bundleName | string | Bundle name of the application that requests the deferred task.|
| abilityName | string | Name of the ability to be notified by a deferred task scheduling callback. This parameter is mandatory.|
| networkType | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | Network type.|
| isCharging | boolean | Whether the device is charging.|
| chargerType | [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | Charging type.|
| batteryLevel | number | Battery level.|
| batteryStatus | [BatteryStatus](../reference/apis/js-apis-resourceschedule-workScheduler.md#batterystatus) | Battery status.|
| storageRequest | [StorageRequest](../reference/apis/js-apis-resourceschedule-workScheduler.md#storagerequest) | Storage status.|
| isRepeat | boolean | Whether the deferred task is repeated.|
| repeatCycleTime | number | Repeat interval.|
| repeatCount | number | Number of repeat times.|
| parameters | [key: string]: number | Carried parameters.|
The **WorkInfo** parameter is used to set conditions for triggering task scheduling. Its setting must comply with the following rules:
- **workId**, **bundleName**, and **abilityName** are mandatory. **bundleName** must be set to the bundle name of the current application.
- The carried parameters can be of the number, string, or boolean type.
- At least one condition must be set, including the network type, charging type, storage status, battery status, and timing status.
- For repeated tasks, **repeatCycleTime** must be at least 20 minutes. When **isRepeat** is set, you must set **repeatCycleTime** or **repeatCount**.
The table below lists the APIs used for developing deferred task scheduling callbacks. For details about more APIs and their usage, see [@ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks)](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md).
**Table 4** Deferred task scheduling callbacks
| API| Description|
| -------- | -------- |
| onWorkStart(work: WorkInfo): void | Called when the system starts scheduling the deferred task.|
| onWorkStop(work: WorkInfo): void | Called when the system stops scheduling the deferred task.|
## How to Develop
The development of deferred task scheduling consists of two steps: implementing the deferred task scheduling capability and implementing deferred task scheduling.
1. **Implementing the deferred task scheduling capability**: Implement the callbacks for starting and stopping the WorkSchedulerExtensionAbility.
2. **Implementing deferred task scheduling**: Call the **WorkScheduler** APIs to start and stop delayed tasks.
### Implementing Deferred Task Scheduling Callbacks
1. Create a project directory.
In the **./entry/src/main/ets** directory of the project, create a directory and an ArkTS file. For example, create a directory and name it **extension**. In the **extension** directory, create an ArkTS file named **WorkSchedulerExtension.ets** and implement the callbacks for deferred task scheduling.
2. Import the module.
```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
```
3. Implement the lifecycle callbacks for the WorkSchedulerExtensionAbility.
```ts
export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility {
// Callback invoked when the system starts scheduling the deferred task.
onWorkStart(workInfo) {
console.info(`onWorkStart, workInfo = ${JSON.stringify(workInfo)}`);
}
// Callback invoked when the system stops scheduling the deferred task.
onWorkStop(workInfo) {
console.info(`onWorkStop, workInfo is ${JSON.stringify(workInfo)}`);
}
}
```
4. Register the WorkSchedulerExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) and set the tags as follows:
- Set **type** to **workScheduler**.
- Set **srcEntry** to the code path of the WorkSchedulerExtensionAbility component.
```json
{
"module": {
"extensionAbilities": [
{
"name": "MyWorkSchedulerExtensionAbility",
"srcEntry": "./ets/WorkSchedulerExtension/WorkSchedulerExtension.ts",
"label": "$string:WorkSchedulerExtensionAbility_label",
"description": "$string:WorkSchedulerExtensionAbility_desc",
"type": "workScheduler"
}
]
}
}
```
### Implementing Deferred Task Scheduling
1. Import the module.
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler';
```
2. Start a deferred task.
```ts
private workInfo = {
workId: 1,
networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI,
bundleName: 'com.example.application',
abilityName: 'MyWorkSchedulerExtensionAbility'
}
try {
workScheduler.startWork(this.workInfo);
console.info(`startWork success`);
} catch (error) {
console.error(`startWork failed. code is ${error.code} message is ${error.message}`);
}
```
3. Cancel the deferred task.
```ts
private workInfo = {
workId: 1,
networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI,
bundleName: 'com.example.application',
abilityName: 'MyWorkSchedulerExtensionAbility'
}
try {
workScheduler.stopWork(this.workInfo);
console.info(`stopWork success`);
} catch (error) {
console.error(`stopWork failed. code is ${error.code} message is ${error.message}`);
}
```
# WorkSchedulerExtensionAbility Development
If your application needs to execute a non-real-time task or a persistent task, you can harness the Work Scheduler mechanism, which will schedule the task when the preset conditions (including the network type, charging type, storage status, battery status, and timing status) are met.
**WorkSchedulerExtensionAbility** provides callbacks for Work Scheduler tasks. When a Work Scheduler task starts or stops, these callbacks are invoked to process your service logic.
## Working Principles
Figure 1 shows the working principle of Work Scheduler.
**Figure 1** Work Scheduler working principle
![WorkSchedulerExtensionAbility](figures/WorkSchedulerExtensionAbility.png)
An application starts, stops, and obtains Work Scheduler tasks through the [workScheduler APIs](../reference/apis/js-apis-resourceschedule-workScheduler.md).
The application service layer detects and determines the conditions. If the preset conditions are met, the application service layer calls back the **WorkSchedulerExtensionAbility** object to start the application and triggers the **onWorkStart** and **onWorkStop** callbacks.
## Available APIs
The **WorkSchedulerExtensionAbility** class has the following APIs. For details, see [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md).
| Name| Description|
| -------- | -------- |
| onWorkStart(work: workScheduler.WorkInfo): void | Called when the Work Scheduler task starts.|
| onWorkStop(work: workScheduler.WorkInfo): void | Called when the Work Scheduler task stops.|
## How to Develop
To create a WorkScheduler project in DevEco Studio, perform the following steps:
- [Implement callbacks for Work Scheduler](#implementing-callbacks-for-work-scheduler): Develop the callbacks provided by **WorkSchedulerExtensionAbility**.
- [Implement Work Scheduler](#implementing-work-scheduler): Develop the [workScheduler APIs] to implement functions such as starting or stopping Work Scheduler tasks.
- [Set the configuration file](#setting-the-configuration-file): Set the configuration file **module.json5**.
### Implementing Callbacks for Work Scheduler
1. Create a module named **library** in the root directory of the project, with the **Ohos Library** template selected.
2. In the **./library/src/main/ets** directory under **library**, create an ArkTS file named **workAbility.ets** and implement the callbacks for Work Scheduler.
Import the module.
```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
```
Implement the lifecycle callbacks for the WorkSchedulerExtensionAbility.
```ts
export default class workAbility extends WorkSchedulerExtensionAbility {
// Callback invoked when the Work Scheduler task starts.
onWorkStart(workInfo) {
console.log(`onWorkStart CommonEvent publish start ${JSON.stringify(workInfo)}`);
// Publish an upgrade notification.
let notificationRequest = notification.getNotificationContentBasic('upgrade', upgradeMessage, '');
notification.publish(notificationRequest, (err) => {
if (err) {
console.log(`onWorkStart notification publish err ${JSON.stringify(err)}`);
}
console.log(`onWorkStart notification publish success`);
});
}
// Callback invoked when the Work Scheduler task stops.
onWorkStop(workInfo) {
// Publish an upgrade completion notification.
let notificationRequest = notification.getNotificationContentBasic('upgrade', 'upgrade success', '');
notification.publish(notificationRequest, (err) => {
if (err) {
console.log(`onWorkStop notification publish err ${JSON.stringify(err)}`);
}
console.log(`onWorkStop notification publish success`);
});
}
}
```
3. In the **./entry/src/main/ets** directory under the **entry** module of the project, create a directory named **workAbility**. In the **workAbility** directory, create an ArkTS file named **WorkTest.ets** and implement the callbacks for Work Scheduler.
Import the module.
```ts
import { workAbility } from '@ohos/library'
```
Inherit from **workAbility** and implement the lifecycle callbacks for the WorkSchedulerExtensionAbility.
```ts
export default class WorkTest extends workAbility {
onWorkStart(workInfo) {
console.log(`onWorkStartTest start ${JSON.stringify(workInfo)}`);
super.onWorkStart(workInfo);
}
onWorkStopTest(workInfo) {
super.onWorkStop(workInfo);
console.log(`onWorkStop value`);
}
}
```
### Implementing Work Scheduler
1. In the **./library/src/main/ets** directory under **library**, create a TypeScript file named **DelayWork.ts**, and implement the Work Scheduler APIs.
Import the module.
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler';
```
Encapsulate the APIs for starting and stopping Work Scheduler tasks.
```ts
export default class DelayWork {
private workInfo = {
workId: 1,
networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI,
bundleName: '',
abilityName: ''
}
// Start the Work Scheduler task.
startWork(bundleName: string, abilityName: string) {
this.workInfo.bundleName = bundleName;
this.workInfo.abilityName = abilityName;
try {
workScheduler.startWork(this.workInfo);
console.log(`startWork success`);
} catch (error) {
Logger.error(TAG, `startWork startwork failed. code is ${error.code} message is ${error.message}`);
prompt.showToast({
message: `${error.message}`
});
}
}
// Stop the Work Scheduler task.
stopWork(bundleName: string, abilityName: string) {
this.workInfo.bundleName = bundleName;
this.workInfo.abilityName = abilityName;
workScheduler.stopWork(this.workInfo, false);
console.log(`stopWork`);
}
}
```
2. In the **./entry/src/main/ets/pages/index.ets** directory under the **entry** module of the project, add the **Upgrade** button, which, when being clicked, will call the API encapsulated in **library** to start the Work Scheduler task.
Import the module.
```ts
import { workAbility } from '@ohos/library';
```
Add the **Upgrade** button, which, when being clicked, will call the API encapsulated in **library** to start the Work Scheduler task. In the API, **bundleName** and **abilityName** are passed in, where the value of **abilityName** is **WorkTest**.
```ts
Button($r('app.string.upgrade'))
.width('60%')
.height(40)
.fontSize(30)
.onClick(() => {
this.work.startWork('ohos.samples.workscheduler', 'WorkTest');
});
```
When the component is destructed, it calls the API to stop the Work Scheduler task.
```ts
aboutToDisappear() {
this.work.stopWork('ohos.samples.workscheduler', 'WorkTest');
}
```
### Setting the Configuration File
1. Register the WorkSchedulerExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) under the **entry** module. Set **type** to **workScheduler** and **srcEnty** to the code path of the WorkSchedulerExtensionAbility component.
```json
{
"module": {
"extensionAbilities": [
{
"name": "WorkTest",
"srcEntry": "./ets/workAbility/WorkTest.ets",
"label": "$string:WorkSchedulerExtensionAbility_label",
"description": "$string:WorkSchedulerExtensionAbility_desc",
"type": "workScheduler"
}
]
}
}
```
## Restrictions
To minimize the abuse of **WorkSchedulerExtensionAbility** by third-party applications, the following APIs cannot be invoked in **WorkSchedulerExtensionAbility**:
- @ohos.backgroundTaskManager.d.ts
- @ohos.resourceschedule.backgroundTaskManager.d.ts
- @ohos.multimedia.camera.d.ts
- @ohos.multimedia.audio.d.ts
- @ohos.multimedia.media.d.ts
...@@ -43,41 +43,44 @@ ...@@ -43,41 +43,44 @@
- [Resource Categories and Access](quick-start/resource-categories-and-access.md) - [Resource Categories and Access](quick-start/resource-categories-and-access.md)
- Learning ArkTS - Learning ArkTS
- [Getting Started with ArkTS](quick-start/arkts-get-started.md) - [Getting Started with ArkTS](quick-start/arkts-get-started.md)
- Basic Syntax - [Introduction to ArkTS]quick-start/arkts/introduction-to-arkts.md)
- [Basic Syntax Overview](quick-start/arkts-basic-syntax-overview.md) - [TypeScript to ArkTS Migration](quick-start/arkts/typescript-to-arkts-migration-guide.md)
- [Declarative UI Description](quick-start/arkts-declarative-ui-description.md) - UI Paradigm
- Custom Component - Basic Syntax
- [Creating a Custom Component](quick-start/arkts-create-custom-components.md) - [Basic Syntax Overview](quick-start/arkts-basic-syntax-overview.md)
- [Page and Custom Component Lifecycle](quick-start/arkts-page-custom-components-lifecycle.md) - [Declarative UI Description](quick-start/arkts-declarative-ui-description.md)
- [\@Builder Decorator: Custom Builder Function](quick-start/arkts-builder.md) - Custom Component
- [\@BuilderParam Decorator: \@Builder Function Reference](quick-start/arkts-builderparam.md) - [Creating a Custom Component](quick-start/arkts-create-custom-components.md)
- [\@Styles Decorator: Definition of Resusable Styles](quick-start/arkts-style.md) - [Page and Custom Component Lifecycle](quick-start/arkts-page-custom-components-lifecycle.md)
- [\@Extend Decorator: Extension of Built-in Components](quick-start/arkts-extend.md) - [\@Builder Decorator: Custom Builder Function](quick-start/arkts-builder.md)
- [stateStyles: Polymorphic Style](quick-start/arkts-statestyles.md) - [\@BuilderParam Decorator: \@Builder Function Reference](quick-start/arkts-builderparam.md)
- [\@AnimatableExtend Decorator: Definition of Animatable Attributes](quick-start/arkts-animatable-extend.md) - [\@Styles Decorator: Definition of Resusable Styles](quick-start/arkts-style.md)
- State Management - [\@Extend Decorator: Extension of Built-in Components](quick-start/arkts-extend.md)
- [State Management Overview](quick-start/arkts-state-management-overview.md) - [stateStyles: Polymorphic Style](quick-start/arkts-statestyles.md)
- Component State Management - [\@AnimatableExtend Decorator: Definition of Animatable Attributes](quick-start/arkts-animatable-extend.md)
- [\@State Decorator: State Owned by Component](quick-start/arkts-state.md) - State Management
- [\@Prop Decorator: One-Way Synchronization from Parent to Child Components](quick-start/arkts-prop.md) - [State Management Overview](quick-start/arkts-state-management-overview.md)
- [\@Link Decorator: Two-Way Synchronization Between Parent and Child Components](quick-start/arkts-link.md) - Component State Management
- [\@Provide and \@Consume Decorators: Two-Way Synchronization with Descendant Components](quick-start/arkts-provide-and-consume.md) - [\@State Decorator: State Owned by Component](quick-start/arkts-state.md)
- [\@Observed and \@ObjectLink Decorators: Observing Attribute Changes in Nested Class Objects](quick-start/arkts-observed-and-objectlink.md) - [\@Prop Decorator: One-Way Synchronization from Parent to Child Components](quick-start/arkts-prop.md)
- Application State Management - [\@Link Decorator: Two-Way Synchronization Between Parent and Child Components](quick-start/arkts-link.md)
- [Application State Management Overview](quick-start/arkts-application-state-management-overview.md) - [\@Provide and \@Consume Decorators: Two-Way Synchronization with Descendant Components](quick-start/arkts-provide-and-consume.md)
- [LocalStorage: UI State Storage](quick-start/arkts-localstorage.md) - [\@Observed and \@ObjectLink Decorators: Observing Attribute Changes in Nested Class Objects](quick-start/arkts-observed-and-objectlink.md)
- [AppStorage: Application-wide UI State Storage](quick-start/arkts-appstorage.md) - Application State Management
- [PersistentStorage: Application State Persistence](quick-start/arkts-persiststorage.md) - [Application State Management Overview](quick-start/arkts-application-state-management-overview.md)
- [Environment: Device Environment Query](quick-start/arkts-environment.md) - [LocalStorage: UI State Storage](quick-start/arkts-localstorage.md)
- Other State Management Features - [AppStorage: Application-wide UI State Storage](quick-start/arkts-appstorage.md)
- [Overview of Other State Management Features](quick-start/arkts-other-state-mgmt-functions-overview.md) - [PersistentStorage: Application State Persistence](quick-start/arkts-persiststorage.md)
- [\@Watch Decorator: Getting Notified of State Variable Changes](quick-start/arkts-watch.md) - [Environment: Device Environment Query](quick-start/arkts-environment.md)
- [$$ Syntax: Two-Way Synchronization of Built-in Components](quick-start/arkts-two-way-sync.md) - Other State Management Features
- Rendering Control - [Overview of Other State Management Features](quick-start/arkts-other-state-mgmt-functions-overview.md)
- [Overview of Rendering Control](quick-start/arkts-rendering-control-overview.md) - [\@Watch Decorator: Getting Notified of State Variable Changes](quick-start/arkts-watch.md)
- [if/else: Conditional Rendering](quick-start/arkts-rendering-control-ifelse.md) - [$$ Syntax: Two-Way Synchronization of Built-in Components](quick-start/arkts-two-way-sync.md)
- [ForEach: Rendering of Repeated Content](quick-start/arkts-rendering-control-foreach.md) - Rendering Control
- [LazyForEach: Lazy Data Loading](quick-start/arkts-rendering-control-lazyforeach.md) - [Overview of Rendering Control](quick-start/arkts-rendering-control-overview.md)
- [if/else: Conditional Rendering](quick-start/arkts-rendering-control-ifelse.md)
- [ForEach: Rendering of Repeated Content](quick-start/arkts-rendering-control-foreach.md)
- [LazyForEach: Lazy Data Loading](quick-start/arkts-rendering-control-lazyforeach.md)
- Development - Development
- Application Models - Application Models
- Application Model Overview - Application Model Overview
...@@ -528,7 +531,9 @@ ...@@ -528,7 +531,9 @@
- [hapsigner Guide](security/hapsigntool-guidelines.md) - [hapsigner Guide](security/hapsigntool-guidelines.md)
- [HarmonyAppProvision Configuration File](security/app-provision-structure.md) - [HarmonyAppProvision Configuration File](security/app-provision-structure.md)
- AI - AI
- [Using MindSpore Lite for Model Inference (JS)](ai/mindspore-lite-js-guidelines.md) - [AI Development](./ai/ai-overview.md)
- [Using MindSpore Lite JavaScript APIs to Develop AI Applications](./ai/mindspore-guidelines-based-js.md)
- [Using MindSpore Lite Native APIs to Develop AI Applications](./ai/mindspore-guidelines-based-native.md)
- Connectivity - Connectivity
- Network Management - Network Management
- [Network Management Overview](connectivity/net-mgmt-overview.md) - [Network Management Overview](connectivity/net-mgmt-overview.md)
...@@ -564,10 +569,14 @@ ...@@ -564,10 +569,14 @@
- [Database Backup and Restoration](database/data-backup-and-restore.md) - [Database Backup and Restoration](database/data-backup-and-restore.md)
- [Database Encryption](database/data-encryption.md) - [Database Encryption](database/data-encryption.md)
- [Access Control by Device and Data Level](database/access-control-by-device-and-data-level.md) - [Access Control by Device and Data Level](database/access-control-by-device-and-data-level.md)
- Cross-Application Data Sharing (for System Applications Only) - Cross-Application Data Sharing
- [Cross-Application Data Sharing Overview](database/share-device-data-across-apps-overview.md) - [Data Sharing Overview](database/data-share-overview.md)
- [Sharing Data Using DataShareExtensionAbility](database/share-data-by-datashareextensionability.md) - [Unified Data Definition](database/unified-data-definition.md)
- [Data Sharing Through Silent Access](database/share-data-by-silent-access.md) - One-to-Many Data Sharing (for System Applications Only)
- [Sharing Data Using DataShareExtensionAbility](database/share-data-by-datashareextensionability.md)
- [Data Sharing Through Silent Access](database/share-data-by-silent-access.md)
- Many-to-Many Data Sharing
- [Sharing Data via Unified Data Channels](database/unified-data-channels.md)
- File Management - File Management
- [File Management Overview](file-management/file-management-overview.md) - [File Management Overview](file-management/file-management-overview.md)
- Application File - Application File
...@@ -601,16 +610,12 @@ ...@@ -601,16 +610,12 @@
- [Setting the Security Level of a Distributed File](file-management/set-security-label.md) - [Setting the Security Level of a Distributed File](file-management/set-security-label.md)
- [Accessing Files Across Devices](file-management/file-access-across-devices.md) - [Accessing Files Across Devices](file-management/file-access-across-devices.md)
- Background Task Management - Background Task Management
- Background Task - [Background Task Overview](task-management/background-task-overview.md)
- [Background Task Management Overview](task-management/background-task-overview.md) - [Transient Task](task-management/transient-task.md)
- [Transient Task Development](task-management/transient-task-dev-guide.md) - [Continuous Task](task-management/continuous-task.md)
- [Continuous Task Development](task-management/continuous-task-dev-guide.md) - [Deferred Task](task-management/work-scheduler.md)
- [Work Scheduler Development](task-management/work-scheduler-dev-guide.md) - [Agent-powered Reminder](task-management/agent-powered-reminder.md)
- [WorkSchedulerExtensionAbility Development](task-management/workscheduler-extensionability.md) - [Requesting Efficiency Resources (for Privileged System Applications Only)](task-management/efficiency-resource-request.md)
- [Efficiency Resource Request Development](task-management/efficiency-resources-apply-dev-guide.md)
- Agent-Powered Reminder
- [Agent-Powered Reminder Overview](task-management/reminder-agent-overview.md)
- [Agent-Powered Reminder Development](task-management/reminder-agent-development.md)
- Device Management - Device Management
- USB Service - USB Service
- [USB Service Overview](device/usb-overview.md) - [USB Service Overview](device/usb-overview.md)
...@@ -930,9 +935,9 @@ ...@@ -930,9 +935,9 @@
- [@ohos.distributedMissionManager (Distributed Mission Management)](reference/apis/js-apis-distributedMissionManager.md) - [@ohos.distributedMissionManager (Distributed Mission Management)](reference/apis/js-apis-distributedMissionManager.md)
- [@ohos.reminderAgentManager (reminderAgentManager)](reference/apis/js-apis-reminderAgentManager.md) - [@ohos.reminderAgentManager (reminderAgentManager)](reference/apis/js-apis-reminderAgentManager.md)
- [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](reference/apis/js-apis-resourceschedule-backgroundTaskManager.md) - [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](reference/apis/js-apis-resourceschedule-backgroundTaskManager.md)
- [@ohos.resourceschedule.workScheduler (Work Scheduler)](reference/apis/js-apis-resourceschedule-workScheduler.md) - [@ohos.resourceschedule.workScheduler (Deferred Task Scheduling)](reference/apis/js-apis-resourceschedule-workScheduler.md)
- [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md) - [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md)
- [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](reference/apis/js-apis-WorkSchedulerExtensionAbility.md) - [@ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks)](reference/apis/js-apis-WorkSchedulerExtensionAbility.md)
- application - application
- [WorkSchedulerExtensionContext](reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md) - [WorkSchedulerExtensionContext](reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md)
- Security - Security
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册