未验证 提交 7b5d2db2 编写于 作者: O openharmony_ci 提交者: Gitee

!2088 Done! 1889:修改后台任务管理文档说明

Merge pull request !2088 from wusongqing/TR1889
......@@ -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&nbsp;requestSuspendDelay(reason:&nbsp;string,&nbsp;callback:&nbsp;Callback&lt;void&gt;):&nbsp;**DelaySuspendInfo**; | Requests delayed suspension after the application switches to the background. <br/>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&nbsp;getRemainingDelayTime(requestId:&nbsp;number,&nbsp;callback:&nbsp;AsyncCallback&lt;number&gt;):&nbsp;void;<br/>function&nbsp;getRemainingDelayTime(requestId:&nbsp;number):&nbsp;Promise&lt;number&gt;; | Obtains the remaining duration before the application is suspended. (The value of **requestId** is obtained from the return value of **requestSuspendDelay**.)<br/>Two asynchronous methods are provided: callback and promise.|
| function&nbsp;requestSuspendDelay(reason:&nbsp;string,&nbsp;callback:&nbsp;Callback&lt;void&gt;):&nbsp;**DelaySuspendInfo**; | Requests delayed suspension after the application switches to the background.<br>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&nbsp;getRemainingDelayTime(requestId:&nbsp;number,&nbsp;callback:&nbsp;AsyncCallback&lt;number&gt;):&nbsp;void;<br>function&nbsp;getRemainingDelayTime(requestId:&nbsp;number):&nbsp;Promise&lt;number&gt;; | Obtains the remaining duration before the application is suspended. (The value of **requestId** is obtained from the return value of **requestSuspendDelay**.)<br>Two asynchronous methods are provided: callback and promise.|
| function&nbsp;cancelSuspendDelay(requestId:&nbsp;number):&nbsp;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&lt;void&gt;): void;<br>function 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.|
| function stopBackgroundRunning(context: Context, callback: AsyncCallback&lt;void&gt;): void;<br>function stopBackgroundRunning(context: Context): Promise&lt;void&gt;; | 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');
}
};
```
# 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.
# 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&lt;number&gt;): 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&lt;number&gt;
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. <br/>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.<br>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&lt;void&gt;): void; <sup>8+</sup>
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&lt;void&gt; | 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&lt;void&gt;; <sup>8+</sup>
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\<void> | 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&lt;void&gt;): void; <sup>8+</sup>
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&lt;void&gt; | 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&lt;void&gt;; <sup>8+</sup>
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\<void> | 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);
});
```
## BackgroundMode<sup>8+</sup>
**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).|
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册