diff --git a/en/application-dev/background-task-management/background-task-dev-guide.md b/en/application-dev/background-task-management/background-task-dev-guide.md
index aeab15fa9cc2ab9831147299d0c6b2ed803e88ca..c504299cc8de51b6a992545fb939154cb5365a82 100644
--- a/en/application-dev/background-task-management/background-task-dev-guide.md
+++ b/en/application-dev/background-task-management/background-task-dev-guide.md
@@ -7,16 +7,18 @@ If a service needs to be continued when the application or service module is run
## Available APIs
-```
+```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
```
-**Table 1** Main APIs of backgroundTaskManager
+## Transient Tasks
+
+**Table 1** Main APIs for transient tasks
| API| Description|
| -------- | -------- |
-| function requestSuspendDelay(reason: string, callback: Callback<void>): **DelaySuspendInfo**; | Requests delayed suspension after the application switches to the background.
The default duration of delayed suspension is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.|
-| function getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void;
function getRemainingDelayTime(requestId: number): Promise<number>; | Obtains the remaining duration before the application is suspended. (The value of **requestId** is obtained from the return value of **requestSuspendDelay**.)
Two asynchronous methods are provided: callback and promise.|
+| function requestSuspendDelay(reason: string, callback: Callback<void>): **DelaySuspendInfo**; | Requests delayed suspension after the application switches to the background.
The default duration of delayed suspension is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.|
+| function getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void;
function getRemainingDelayTime(requestId: number): Promise<number>; | Obtains the remaining duration before the application is suspended. (The value of **requestId** is obtained from the return value of **requestSuspendDelay**.)
Two asynchronous methods are provided: callback and promise.|
| function cancelSuspendDelay(requestId: number): void; | Cancels the suspension delay. (The value of **requestId** is obtained from the return value of **requestSuspendDelay**.)|
**Table 2** Parameters in DelaySuspendInfo
@@ -29,51 +31,221 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager';
## How to Develop
+
1. Request a suspension delay.
- ```
- import backgroundTaskManager from '@ohos.backgroundTaskManager';
- let myReason = 'test requestSuspendDelay';
- let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
- console.info("Request suspension delay will time out.");
- });
- var id = delayInfo.requestId;console.info("requestId is: " + id);
- ```
+
+ ```js
+ import backgroundTaskManager from '@ohos.backgroundTaskManager';
+
+ let myReason = 'test requestSuspendDelay';
+ let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
+ console.info("Request suspension delay will time out.");
+ });
+
+ var id = delayInfo.requestId;console.info("requestId is: " + id);
+ ```
+
2. Obtain the remaining duration before the application is suspended.
- ```
- backgroundTaskManager.getRemainingDelayTime(id).then( res => {
- console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res));
- }).catch( err => {
- console.log('promise => Operation failed. Cause: ' + err.data);
- });
- ```
+
+ ```js
+ backgroundTaskManager.getRemainingDelayTime(id).then( res => {
+ console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res));
+ }).catch( err => {
+ console.log('promise => Operation failed. Cause: ' + err.data);
+ });
+ ```
+
3. Cancel the suspension delay.
- ```
- backgroundTaskManager.cancelSuspendDelay(id);
- ```
+
+ ```js
+ backgroundTaskManager.cancelSuspendDelay(id);
+ ```
## Development Examples
-```
+```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
let myReason = 'test requestSuspendDelay';
+
// Request a suspension delay.
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
console.info("Request suspension delay will time out.");
});
+
// Print the suspension delay information.
var id = delayInfo.requestId;
var time = delayInfo.actualDelayTime;
console.info("The requestId is: " + id);
console.info("The actualDelayTime is: " + time);
+
// Obtain the remaining duration before the application is suspended.
backgroundTaskManager.getRemainingDelayTime(id).then( res => {
console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res));
}).catch( err => {
console.log('promise => Operation failed. Cause: ' + err.data);
});
+
// Cancel the suspension delay.
backgroundTaskManager.cancelSuspendDelay(id);
```
+
+## Continuous Tasks
+
+### Required Permissions
+
+ohos.permission.KEEP_BACKGROUND_RUNNING
+
+**Table 3** Main APIs for continuous tasks
+
+| API| Description|
+| -------- | -------- |
+| function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void;
function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void>; | Requests a continuous task from the system so that the application keeps running in the background.|
+| function stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void;
function stopBackgroundRunning(context: Context): Promise<void>; | Cancels the continuous task.|
+
+
+For details about **WantAgent**, see [WantAgent](../reference/apis/js-apis-notification.md#WantAgent).
+
+
+**Table 4** Background modes
+| Name| ID Value| Description|
+| -------- | -------- | -------- |
+| DATA_TRANSFER | 1 | Data transfer.|
+| AUDIO_PLAYBACK | 2 | Audio playback.|
+| AUDIO_RECORDING | 3 | Audio recording.|
+| LOCATION | 4 | Positioning and navigation.|
+| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task.|
+| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection.|
+| WIFI_INTERACTION | 7 | WLAN-related task (reserved).|
+| VOIP | 8 | Voice and video call (reserved).|
+| TASK_KEEPING | 9 | Computing task (for PC only).|
+
+
+## How to Develop
+
+1. Declare the continuous task permission in the **config.json** file.
+
+ ```json
+ "module": {
+ "package": "com.example.myapplication",
+ ...,
+ "reqPermissions": [
+ {
+ "name": "ohos.permission.KEEP_BACKGROUND_RUNNING"
+ }
+ ]
+ }
+ ```
+
+2. Request a continuous task.
+
+ ```js
+ import backgroundTaskManager from '@ohos.backgroundTaskManager';
+ import featureAbility from '@ohos.ability.featureAbility';
+ import wantAgent from '@ohos.wantAgent';
+
+ let wantAgentInfo = {
+ wants: [
+ {
+ bundleName: "com.example.myapplication",
+ abilityName: "com.example.myapplication.MainAbility"
+ }
+ ],
+ operationType: wantAgent.OperationType.START_ABILITY,
+ requestCode: 0,
+ wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG]
+ };
+
+ // Obtain the WantAgent object by using the getWantAgent method of the wantAgent module.
+ wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
+ backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
+ backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
+ console.info("Operation succeeded");
+ }).catch((err) => {
+ console.error("Operation failed Cause: " + err);
+ });
+ });
+ ```
+
+3. Cancel the continuous task.
+
+ ```js
+ import backgroundTaskManager from '@ohos.backgroundTaskManager';
+ import featureAbility from '@ohos.ability.featureAbility';
+
+ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
+ console.info("Operation succeeded");
+ }).catch((err) => {
+ console.error("Operation failed Cause: " + err);
+ });
+
+ ```
+
+## Development Examples
+
+After a service is started, call the API for requesting a continuous task in the **onStart** callback of the Service ability to declare that the service needs to run in the background for a long time. In the **onStop** callback, call the API for canceling the continuous task.
+In the **service.js** file:
+
+```js
+import backgroundTaskManager from '@ohos.backgroundTaskManager';
+import featureAbility from '@ohos.ability.featureAbility';
+import wantAgent from '@ohos.wantAgent';
+
+function startBackgroundRunning() {
+ let wantAgentInfo = {
+ wants: [
+ {
+ bundleName: "com.example.myapplication",
+ abilityName: "com.example.myapplication.MainAbility"
+ }
+ ],
+ operationType: wantAgent.OperationType.START_ABILITY,
+ requestCode: 0,
+ wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG]
+ };
+
+ // Obtain the WantAgent object by using the getWantAgent method of the wantAgent module.
+ wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
+ backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
+ backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
+ console.info("Operation succeeded");
+ }).catch((err) => {
+ console.error("Operation failed Cause: " + err);
+ });
+ });
+}
+
+function stopBackgroundRunning() {
+ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
+ console.info("Operation succeeded");
+ }).catch((err) => {
+ console.error("Operation failed Cause: " + err);
+ });
+}
+
+export default {
+ onStart(want) {
+ console.info('ServiceAbility onStart');
+ startBackgroundRunning();
+ },
+ onStop() {
+ console.info('ServiceAbility onStop');
+ stopBackgroundRunning();
+ },
+ onConnect(want) {
+ console.info('ServiceAbility onConnect');
+ return {};
+ },
+ onReconnect(want) {
+ console.info('ServiceAbility onReconnect');
+ },
+ onDisconnect() {
+ console.info('ServiceAbility onDisconnect');
+ },
+ onCommand(want, restart, startId) {
+ console.info('ServiceAbility onCommand');
+ }
+};
+```
diff --git a/en/application-dev/background-task-management/background-task-overview.md b/en/application-dev/background-task-management/background-task-overview.md
index 3483ae70d0e05a4613f7efa031494401f867a88a..17280fd450b6ba47629735f912969b22fb5a4f27 100644
--- a/en/application-dev/background-task-management/background-task-overview.md
+++ b/en/application-dev/background-task-management/background-task-overview.md
@@ -1,4 +1,4 @@
-# Background Task Management Overview
+# Background Task Overview
On an OS that allows for user interaction, resources gravitate to service processes that interact with users. In other words, apart from processes that support system running, service processes that can be perceived by users have the highest priority. Therefore, background task management is applicable to service processes that cannot be perceived by users.
@@ -33,3 +33,30 @@ Adhere to the following constraints and rules when using transient tasks:
- **When to cancel**: The requesting application shall cancel the request when the transient task is complete. If the request is forcibly canceled by the system, the time frame allowed for the application to run in the background will be affected.
- **Quota mechanism**: To prevent abuse of the keepalive, each application has a certain quota every day (dynamically adjusted based on user habits). 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.)
+
+## Continuous Tasks
+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 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 upload, download, backup, and restore| 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 | 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|
+| 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| PC-specific, valid only on PCs|
+
+### Restrictions on Using Continuous Tasks
+- If a user triggers a perceivable task, such as broadcasting, navigation, upload, and download, 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.
+- Each ability can request only one continuous task at a time.
diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md
index e9962bab099f10ea3a8e662d6615ba31c1c6f574..0af0d28745ed605684167b9f9191d02f3e68b992 100644
--- a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md
+++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md
@@ -1,6 +1,6 @@
# Background Task Management
-> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:**
+> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
@@ -10,10 +10,11 @@
import backgroundTaskManager from '@ohos.backgroundTaskManager';
```
-
## Required Permissions
-None
+Declare the following permissions for continuous tasks:
+
+ohos.permission.KEEP_BACKGROUND_RUNNING
## backgroundTaskManager.requestSuspendDelay
@@ -24,6 +25,8 @@ Requests delayed suspension after the application switches to the background.
The default duration of delayed suspension is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.
+**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
+
- **Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
@@ -48,7 +51,9 @@ The default duration of delayed suspension is 180000 when the battery level is h
getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void
-Obtains the remaining duration before the application is suspended. This method uses an asynchronous callback to return the result.
+Obtains the remaining duration before the application is suspended. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
- **Parameters**
| Name| Type| Mandatory| Description|
@@ -73,7 +78,9 @@ Obtains the remaining duration before the application is suspended. This method
getRemainingDelayTime(requestId: number): Promise<number>
-Obtains the remaining duration before the application is suspended. This method uses a promise to return the result.
+Obtains the remaining duration before the application is suspended. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
- **Parameters**
| Name| Type| Mandatory| Description|
@@ -102,6 +109,8 @@ cancelSuspendDelay(requestId: number): void
Cancels the suspension delay.
+**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
+
- **Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
@@ -117,7 +126,186 @@ Cancels the suspension delay.
Provides the information about the suspension delay.
+**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
+
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| requestId | number | Yes| ID of the suspension delay request.|
-| actualDelayTime | number | Yes| Actual suspension delay duration of the application, in milliseconds.
The default duration is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.|
+| actualDelayTime | number | Yes| Actual suspension delay duration of the application, in milliseconds.
The default duration is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.|
+
+## backgroundTaskManager.startBackgroundRunning
+
+startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void; 8+
+
+Requests a continuous task from the system. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
+
+- **Parameters**
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | context | Context | Yes| Application context.|
+ | bgMode | BackgroundMode | Yes| Background mode requested.|
+ | wantAgent | [WantAgent](js-apis-notification.md#WantAgent)| Yes| Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked.|
+ | callback | AsyncCallback<void> | Yes| Callback used to return the result.|
+
+- **Example**
+```js
+import backgroundTaskManager from '@ohos.backgroundTaskManager';
+import featureAbility from '@ohos.ability.featureAbility';
+import wantAgent from '@ohos.wantAgent';
+
+function callback(err, data) {
+ if (err) {
+ console.error("Operation failed Cause: " + err);
+ } else {
+ console.info("Operation succeeded");
+ }
+}
+
+let wantAgentInfo = {
+ wants: [
+ {
+ bundleName: "com.example.myapplication",
+ abilityName: "com.example.myapplication.MainAbility"
+ }
+ ],
+ operationType: wantAgent.OperationType.START_ABILITY,
+ requestCode: 0,
+ wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG]
+};
+
+wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
+ backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
+ backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj, callback)
+});
+
+```
+
+## backgroundTaskManager.startBackgroundRunning
+
+startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void>; 8+
+
+Requests a continuous task from the system. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
+
+- **Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | context | Context | Yes| Application context.|
+ | bgMode | BackgroundMode | Yes| Background mode requested.|
+| wantAgent | [WantAgent](js-apis-notification.md#WantAgent)| Yes| Notification parameter, which is used to specify the target page when a continuous task notification is clicked.|
+
+- **Return value**
+ | Type | Description |
+ | -------------- | ------------------------- |
+ | Promise\ | Promise used to return the result.|
+
+- **Example**
+```js
+import backgroundTaskManager from '@ohos.backgroundTaskManager';
+import featureAbility from '@ohos.ability.featureAbility';
+import wantAgent from '@ohos.wantAgent';
+
+let wantAgentInfo = {
+ wants: [
+ {
+ bundleName: "com.example.myapplication",
+ abilityName: "com.example.myapplication.MainAbility"
+ }
+ ],
+ operationType: wantAgent.OperationType.START_ABILITY,
+ requestCode: 0,
+ wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG]
+};
+
+wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
+ backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
+ backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
+ console.info("Operation succeeded");
+ }).catch((err) => {
+ console.error("Operation failed Cause: " + err);
+ });
+});
+
+```
+
+## backgroundTaskManager.stopBackgroundRunning
+
+stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void; 8+
+
+Requests to cancel a continuous task. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
+
+- **Parameters**
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | context | Context | Yes| Application context.|
+ | callback | AsyncCallback<void> | Yes| Callback used to return the result.|
+
+- **Example**
+```js
+import backgroundTaskManager from '@ohos.backgroundTaskManager';
+import featureAbility from '@ohos.ability.featureAbility';
+
+function callback(err, data) {
+ if (err) {
+ console.error("Operation failed Cause: " + err);
+ } else {
+ console.info("Operation succeeded");
+ }
+}
+
+backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), callback);
+
+```
+
+## backgroundTaskManager.stopBackgroundRunning
+
+stopBackgroundRunning(context: Context): Promise<void>; 8+
+
+Requests to cancel a continuous task. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
+
+- **Parameters**
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | context | Context | Yes| Application context.|
+
+- **Return value**
+ | Type | Description |
+ | -------------- | ------------------------- |
+ | Promise\ | Promise used to return the result.|
+
+- **Example**
+```js
+import backgroundTaskManager from '@ohos.backgroundTaskManager';
+import featureAbility from '@ohos.ability.featureAbility';
+
+backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
+ console.info("Operation succeeded");
+}).catch((err) => {
+ console.error("Operation failed Cause: " + err);
+});
+
+```
+
+## BackgroundMode8+
+
+**System capability:** SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
+
+| Name | Value| Description|
+| ----------------------- | -------- | -------- |
+| DATA_TRANSFER | 1 | Data transfer.|
+| AUDIO_PLAYBACK | 2 | Audio playback.|
+| AUDIO_RECORDING | 3 | Audio recording.|
+| LOCATION | 4 | Positioning and navigation.|
+| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task.|
+| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection.|
+| WIFI_INTERACTION | 7 | WLAN-related (reserved).|
+| VOIP | 8 | Voice and video call (reserved).|
+| TASK_KEEPING | 9 | Computing task (for PC only).|