未验证 提交 0377de21 编写于 作者: O openharmony_ci 提交者: Gitee

!8290 翻译完成:6977+7547 后台任务管理模块,长时任务补充Stage模型下的开发步骤

Merge pull request !8290 from wusongqing/TR6977
# BackgroundTaskManager
# Background Task Management
This module provides background task management.
The **BackgroundTaskManager** module provides APIs to manage background tasks.
If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task or continuous task for delayed suspension based on the service type.
......@@ -15,7 +15,7 @@ If an application has a service that can be intuitively perceived by users and n
## Modules to Import
```
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
```
......@@ -144,12 +144,12 @@ Requests a continuous task from the system. This API uses an asynchronous callba
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------- | ---- | ------------------------ |
| context | [Context](js-apis-Context.md) | Yes | Application context. |
| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. |
| wantAgent | [WantAgent](js-apis-wantAgent.md) | 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. |
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------- | ---- | ---------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. |
| wantAgent | [WantAgent](js-apis-wantAgent.md) | 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
......@@ -196,11 +196,11 @@ Requests a continuous task from the system. This API uses a promise to return th
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------- | ---- | ----------------------- |
| context | [Context](js-apis-Context.md) | Yes | Application context. |
| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. |
| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked.|
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------- | ---- | ---------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. |
| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. |
**Return value**
| Type | Description |
......@@ -245,10 +245,10 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ----------------------------- | ---- | ---------------------- |
| context | [Context](js-apis-Context.md) | Yes | Application context. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ---------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
**Example**
```js
......@@ -276,9 +276,9 @@ Requests to cancel a continuous task. This API uses a promise to return the resu
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ----------------------------- | ---- | --------- |
| context | [Context](js-apis-Context.md) | Yes | Application context.|
| Name | Type | Mandatory | Description |
| ------- | ------- | ---- | ---------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
**Return value**
| Type | Description |
......@@ -314,14 +314,14 @@ Provides the information about the suspension delay.
**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.<br>This is a system API and cannot be called by third-party applications.|
| VOIP | 8 | Audio and video calls.<br>This is a system API and cannot be called by third-party applications.|
| TASK_KEEPING | 9 | Computing task (effective only for specific devices). |
| 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.<br>This is a system API.|
| VOIP | 8 | Audio and video calls.<br>This is a system API. |
| TASK_KEEPING | 9 | Computing task (effective only for specific devices). |
......@@ -10,11 +10,11 @@ If a service needs to be continued when the application or service module is run
**Table 1** Main APIs for transient tasks
| API| Description|
| -------- | -------- |
| requestSuspendDelay(reason:&nbsp;string,&nbsp;callback:&nbsp;Callback&lt;void&gt;):&nbsp;[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 180000 when the battery level is normal and 60000 when the battery level is low.|
| getRemainingDelayTime(requestId:&nbsp;number):&nbsp;Promise&lt;number&gt; | Obtains the remaining duration before the application is suspended.<br>This API uses a promise to return the task execution result.|
| cancelSuspendDelay(requestId:&nbsp;number):&nbsp;void | Cancels the suspension delay.|
| 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 value of delayed suspension is 180000 when the battery level is normal and 60000 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
......@@ -24,12 +24,12 @@ If a service needs to be continued when the application or service module is run
```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);
```
......@@ -91,31 +91,33 @@ ohos.permission.KEEP_BACKGROUND_RUNNING
**Table 2** Main APIs for continuous tasks
| API| Description|
| -------- | -------- |
| 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.|
| stopBackgroundRunning(context: Context): Promise&lt;void&gt; | Cancels the continuous task. |
For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantAgent.md).
**Table 3** Background modes
| Name| ID| Description| Item|
| -------- | -------- | -------- | -------- |
| DATA_TRANSFER | 1 | Data transfer.| dataTransfer |
| AUDIO_PLAYBACK | 2 | Audio playback.| audioPlayback |
| AUDIO_RECORDING | 3 | Audio recording.| audioRecording |
| LOCATION | 4 | Positioning and navigation.| location |
| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task.| bluetoothInteraction |
| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection.| multiDeviceConnection |
| WIFI_INTERACTION | 7 | WLAN-related task (reserved).| wifiInteraction |
| VOIP | 8 | Voice and video call (reserved).| voip |
| TASK_KEEPING | 9 | Computing task (for specific devices only).| taskKeeping |
| Name | ID | Description | Configuration Item |
| ----------------------- | ---- | -------------- | --------------------- |
| DATA_TRANSFER | 1 | Data transfer. | dataTransfer |
| AUDIO_PLAYBACK | 2 | Audio playback. | audioPlayback |
| AUDIO_RECORDING | 3 | Audio recording. | audioRecording |
| LOCATION | 4 | Positioning and navigation. | location |
| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | bluetoothInteraction |
| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | multiDeviceConnection |
| WIFI_INTERACTION | 7 | WLAN-related task (reserved). | wifiInteraction |
| VOIP | 8 | Voice and video call (reserved). | voip |
| TASK_KEEPING | 9 | Computing task (for specific devices only).| taskKeeping |
### How to Develop
Development on the FA model:
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 and background mode type in the **config.json** file, with the ability type set to **service**.
```
......@@ -137,7 +139,7 @@ For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantA
]
}
```
2. Request a continuous task.
```js
......@@ -173,16 +175,84 @@ For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantA
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';
backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
console.info("Operation stopBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation stopBackgroundRunning failed Cause: " + err);
});
```
Development on the stage model:
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 and background mode type in the **module.json5** file.
```
"module": {
"abilities": [
{
"backgroundModes": [
"dataTransfer",
"location"
], // Background mode
}
],
"requestPermissions": [
{
"name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission
}
]
}
```
2. Request a continuous task.
```ts
import backgroundTaskManager from '@ohos.backgroundTaskManager';
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_PRESENT_FLAG]
};
// Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
backgroundTaskManager.startBackgroundRunning(this.context,
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation startBackgroundRunning failed Cause: " + err);
});
});
```
3. Cancel the continuous task.
```ts
import backgroundTaskManager from '@ohos.backgroundTaskManager';
backgroundTaskManager.stopBackgroundRunning(this.context).then(() => {
console.info("Operation stopBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation stopBackgroundRunning failed Cause: " + err);
});
```
### Development Examples
Development on the FA model:
For details about how to use the Service ability in the FA model, see [Service Ability Development](../ability/fa-serviceability.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.
......@@ -284,3 +354,127 @@ export default {
}
};
```
Development on the stage model:
For details about the stage model, see [Stage Model Overview](../ability/stage-brief.md).
If an application needs to run a continuous task in the background, you can use **Call** to create and run an ability in the background. For details, see [Call Development](../ability/stage-call.md).
```ts
import Ability from '@ohos.application.Ability'
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import wantAgent from '@ohos.wantAgent';
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) => {
backgroundTaskManager.startBackgroundRunning(mContext,
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation startBackgroundRunning failed Cause: " + err);
});
});
}
function stopContinuousTask() {
backgroundTaskManager.stopBackgroundRunning(mContext).then(() => {
console.info("Operation stopBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation stopBackgroundRunning failed Cause: " + err);
});
}
class MySequenceable {
num: number = 0;
str: String = "";
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
return true;
}
}
function sendMsgCallback(data) {
console.info('BgTaskAbility funcCallBack is called ' + data)
let receivedData = new Mysequenceable(0, "")
data.readSequenceable(receivedData)
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`)
if (receivedData.str === 'start_bgtask') {
startContinuousTask()
} else if (receivedData.str === 'stop_bgtask') {
stopContinuousTask();
}
return new Mysequenceable(10, "Callee test");
}
export default class BgTaskAbility extends Ability {
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/second").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")
}
};
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册