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.
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.
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.
## Background Task Types
## Background Task Types
For more targeted management of background applications, OpenHarmony classifies background tasks into the following types and provides an extended resource request mode:
For more targeted management of background applications, OpenHarmony classifies background tasks into the following types and provides an extended resource request mode:
**No background task**: An application or service module does not need further processing when switched to the background.
-**No background task**: 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.
-**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.
-**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.
-**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 CPU, WORK_SCHEDULER, 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.
-**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 CPU, WORK_SCHEDULER, 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.
| dataTransfer | Data transfer through the network or peer device, such as download, backup, share, and transfer| A data transfer task is running.| - |
| 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.| - |
| audioPlayback | Audio output | An audio playback task is running. | - |
| audioRecording | Audio input| A recording task is running.| - |
| audioRecording | Audio input | A recording task is running. | - |
| location | Positioning and navigation| A positioning task is running.| - |
| location | Positioning and navigation | A positioning task is running. | - |
| bluetoothInteraction | Bluetooth transmission| A Bluetooth-related task is running.| - |
| bluetoothInteraction | Bluetooth transmission | A Bluetooth-related task is running. | - |
| multiDeviceConnection | Distributed interconnection| A distributed task is running.| - |
| multiDeviceConnection | Distributed interconnection | A distributed task is running. | - |
| wifiInteraction | WLAN transmission| A WLAN-related task is running.| System API, which is available only to system applications|
| 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|
| 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|
| taskKeeping | Computing task | A computing task is running | Effective only for specific devices |
### Restrictions on Using Continuous Tasks
### 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 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.
...
@@ -80,15 +80,15 @@ The use of the Work Scheduler must comply with the following restrictions and ru
...
@@ -80,15 +80,15 @@ The use of the Work Scheduler must comply with the following restrictions and ru
-**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).
-**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.
-**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 |
| Application Group | Work Scheduler Task Execution Frequency|
| CPU | 1 | CPU resources, which prevent the application from being suspended. |
| CPU | 1 | CPU resources, which prevent the application from being suspended. |
| COMMON_EVENT | 2 | A type of software resources, which prevent common events from being proxied when the application is suspended. |
| COMMON_EVENT | 2 | A type of software resources, which prevent common events from being proxied when the application is suspended. |
| TIMER | 4 | A type of software resources, which prevent timers from being proxied when the application is suspended. |
| TIMER | 4 | A type of software 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. |
| WORK_SCHEDULER | 8 | WORK_SCHEDULER resources, which ensure that the application has more time to execute the task. |
| BLUETOOTH | 16 | A type of hardware resources, which prevent Bluetooth resources from being proxied when the application is suspended. |
| BLUETOOTH | 16 | A type of hardware resources, which prevent Bluetooth resources from being proxied when the application is suspended. |
| GPS | 32 | A type of hardware resources, which prevent GPS resources from being proxied when the application is suspended. |
| GPS | 32 | A type of hardware resources, which prevent GPS resources from being proxied when the application is suspended.|
| AUDIO | 64 | A type of hardware resources, which prevent audio resources from being proxied when the application is suspended.|
| AUDIO | 64 | A type of hardware resources, which prevent audio resources from being proxied when the application is suspended. |
### Restrictions on Using Efficiency Resources
### 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.
- 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.
- 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.
- 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.
- The WORK_SCHEDULER resources can be requested and released by applications, but not by processes.
- To use efficiency resources, an application must first submit a request to the application center to obtain corresponding privileges.
- To use efficiency resources, an application must first submit a request to the application center to obtain corresponding privileges.
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.
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 the task so that the task is perceivable. In addition, the system verifies whether the application is actually executing the continuous task.
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
## Available APIs
...
@@ -15,7 +15,7 @@ There is no time limit for a continuous task running in the background. To preve
...
@@ -15,7 +15,7 @@ There is no time limit for a continuous task running in the background. To preve
| stopBackgroundRunning(context: Context): Promise<void> | Cancels the continuous task. |
| stopBackgroundRunning(context: Context): Promise<void> | Cancels the continuous task. |
For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantAgent.md).
For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md).
**Table 2** Background modes
**Table 2** Background modes
...
@@ -34,152 +34,9 @@ For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantA
...
@@ -34,152 +34,9 @@ For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantA
## How to Develop
## How to Develop
### Development on the FA Model
### Development in the Stage Model
For details about how to use the Service ability in the FA model, see [Service Ability Development](../ability/fa-serviceability.md).
For details about the stage model, see [Stage Model Development Overview](../application-models/stage-model-development-overview.md).
If an application does not need to interact with a continuous task in the background, you can use **startAbility()** to start the Service ability. In the **onStart** callback of the Service ability, call **startBackgroundRunning()** to declare that the Service ability 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 Service ability. After obtaining the proxy of the Service ability, the application can communicate with the Service ability and control the request and cancellation of continuous tasks.
1. Create an API version 8 project. Then right-click the project directory and choose **New > Ability > Service Ability** to create a Service ability. Configure the continuous task permission (**ohos.permission.KEEP_BACKGROUND_RUNNING**) and background mode type in the **config.json** file, with the ability type set to **service**.
For details about the stage model, see [Stage Model Overview](../ability/stage-brief.md).
1. Create an API version 9 project. Then right-click the project directory and choose **New > Ability** to create an ability. Configure the continuous task permission (ohos.permission.KEEP_BACKGROUND_RUNNING) and background mode type in the **module.json5** file.
1. Create an API version 9 project. Then right-click the project directory and choose **New > Ability** to create an ability. Configure the continuous task permission (ohos.permission.KEEP_BACKGROUND_RUNNING) and background mode type in the **module.json5** file.
...
@@ -201,10 +58,10 @@ For details about the stage model, see [Stage Model Overview](../ability/stage-b
...
@@ -201,10 +58,10 @@ For details about the stage model, see [Stage Model Overview](../ability/stage-b
}
}
```
```
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 about how to use an ability in the stage model, see [Ability Development](../ability/stage-ability.md).
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).
// Type of the operation to perform after the notification is clicked.
// Type of the operation to perform after the notification is clicked.
...
@@ -290,14 +147,14 @@ struct Index {
...
@@ -290,14 +147,14 @@ struct Index {
}
}
```
```
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 [Call Development](../ability/stage-call.md).
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-ability-call-to-implement-uiability-interaction) and [Using Ability Call (Inter-Device)](../application-models/hop-multi-device-collaboration.md#using-cross-device-ability-call).
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 Service ability. In the **onStart** callback of the Service ability, call **startBackgroundRunning()** to declare that the Service ability 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 Service ability. After obtaining the proxy of the Service ability, the application can communicate with the Service ability and control the request and cancellation of continuous tasks.
1. Create an API version 8 project. Then right-click the project directory and choose **New > Ability > Service Ability** to create a Service ability. Configure the continuous task permission (**ohos.permission.KEEP_BACKGROUND_RUNNING**) and background mode type in the **config.json** file, with the ability type set to **service**.
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 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.
| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void<br>publishReminder(reminderReq: ReminderRequest): Promise<number> | 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 and 2000 for the entire system. |
| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void<br>publishReminder(reminderReq: ReminderRequest): Promise<number> | 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.|
| cancelReminder(reminderId: number, callback: AsyncCallback<void>): void<br>cancelReminder(reminderId: number): Promise<void> | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)|
| cancelReminder(reminderId: number, callback: AsyncCallback<void>): void<br>cancelReminder(reminderId: number): Promise<void> | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)|
| getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void<br>getValidReminders(): Promise<Array<ReminderRequest>> | Obtains all valid reminders set by the current application. |
| getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void<br>getValidReminders(): Promise<Array<ReminderRequest>> | Obtains all valid reminders set by the current application. |
| cancelAllReminders(callback: AsyncCallback<void>): void<br>cancelAllReminders(): Promise<void> | Cancels all reminders set by the current application. |
| cancelAllReminders(callback: AsyncCallback<void>): void<br>cancelAllReminders(): Promise<void> | Cancels all reminders set by the current application. |
| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void<br>addNotificationSlot(slot: NotificationSlot): Promise<void> | Registers a **NotificationSlot** instance to be used by the reminder. |
| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void<br>addNotificationSlot(slot: NotificationSlot): Promise<void> | Registers a **NotificationSlot** instance to be used by the reminder. |
...
@@ -51,9 +51,9 @@ The agent-powered reminder feature provides APIs for publishing background remin
...
@@ -51,9 +51,9 @@ The agent-powered reminder feature provides APIs for publishing background remin
pkgName: 'com.example.myapplication',
pkgName: 'com.example.myapplication',
abilityName: 'EntryAbility'
abilityName: 'EntryAbility'
},
},
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.
notificationId: 100, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.
notificationId: 100, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.
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.
}
}
...
@@ -94,10 +94,10 @@ The agent-powered reminder feature provides APIs for publishing background remin
...
@@ -94,10 +94,10 @@ The agent-powered reminder feature provides APIs for publishing background remin
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: 5, // 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.
snoozeContent:'remind later', // Content to be displayed when the reminder is snoozed.
snoozeContent:'remind later', // Content to be displayed when the reminder is snoozed.
notificationId: 100, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.
notificationId: 100, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.
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.
}
}
...
@@ -131,10 +131,10 @@ The agent-powered reminder feature provides APIs for publishing background remin
...
@@ -131,10 +131,10 @@ The agent-powered reminder feature provides APIs for publishing background remin
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: 5, // 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.
snoozeContent:'remind later', // Content to be displayed when the reminder is snoozed.
snoozeContent:'remind later', // Content to be displayed when the reminder is snoozed.
notificationId: 99, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.
notificationId: 99, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.
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.
}
}
...
@@ -175,7 +175,3 @@ The agent-powered reminder feature provides APIs for publishing background remin
...
@@ -175,7 +175,3 @@ The agent-powered reminder feature provides APIs for publishing background remin
By default, an application can run for 6 to 12 seconds after it switches to the background but before being suspended. If an application requires more time to execute an important task, it can call the **requestSuspendDelay** API to delay the suspension.
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.
It is recommended that an application calls the **requestSuspendDelay** API before executing any time-consuming task, rather than when it is already running in the background.
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.
The calling of the **requestSuspendDelay** API when the application is running in the foreground does not affect the transient task quota of the application.
Each application has a daily time quota for transient tasks. Therefore, after the time-consuming task finishes execution, the application should cancel the transient task in a timely manner.
An application can obtain the remaining duration before being suspended by calling [getRemainingDelayTime()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagergetremainingdelaytimecallback). 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.
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.
...
@@ -19,43 +18,51 @@ Typical time-consuming tasks include saving status data to the local database, o
...
@@ -19,43 +18,51 @@ Typical time-consuming tasks include saving status data to the local database, o
| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | Requests delayed suspension after the application switches to the background.<br>The default duration value of delayed suspension is 3 minutes when the battery level is normal and 1 minute when the battery level is low.|
| requestSuspendDelay(reason: string, callback: Callback<void>): [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<number> | Obtains the remaining duration before the application is suspended.<br>This API uses a promise to return the result. |
| getRemainingDelayTime(requestId: number): Promise<number> | 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. |
| cancelSuspendDelay(requestId: number): void | Cancels the suspension delay. |
## How to Develop
## How to Develop
1. When an application needs to execute a time-consuming task, call the API to request a transient task. After the time-consuming task finishes execution, call the API to cancel the transient task.
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.
console.info("Request suspension delay will time out.");
// The callback in 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.
// 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;
id=delayInfo.requestId;
console.info("requestId is: "+id);
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.
// Obtain the remaining duration before the application is suspended.
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. For details about the restrictions, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
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
## Available APIs
...
@@ -14,21 +14,21 @@ startWork(work: WorkInfo): void; | Starts a Work Scheduler task.
...
@@ -14,21 +14,21 @@ startWork(work: WorkInfo): void; | Starts a Work Scheduler task.
stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops 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, 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.
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 Work Scheduler tasks. This API uses an asynchronous callback 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 Work Scheduler tasks. This API uses a promise 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 Work Scheduler tasks.
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, 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.
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
**Table 2** WorkInfo parameters
For details about the constraints on configuring **WorkInfo**, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
For details about the restriction on configuring **WorkInfo**, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
2. Develop an Extension ability to execute a Work Scheduler task. For details about the Extension ability, see [ExtensionAbility Mechanism](../ability/stage-brief.md#extensionability-mechanism).
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).
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.
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.
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.
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.
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**.
1. Register the WorkSchedulerExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) under the **entry** module. Set **type** to **workScheduler** and **srcEntrance** to the code path of the WorkSchedulerExtensionAbility component.