From 01a543f968677d322311742d901a9ef2e4159e49 Mon Sep 17 00:00:00 2001 From: wusongqing Date: Fri, 19 Aug 2022 09:21:00 +0800 Subject: [PATCH] update docs against 7553 Signed-off-by: wusongqing --- .../background-task-dev-guide.md | 242 ++++++++++++++++-- 1 file changed, 218 insertions(+), 24 deletions(-) diff --git a/en/application-dev/task-management/background-task-dev-guide.md b/en/application-dev/task-management/background-task-dev-guide.md index e8d85cc571..e820da263f 100644 --- a/en/application-dev/task-management/background-task-dev-guide.md +++ b/en/application-dev/task-management/background-task-dev-guide.md @@ -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: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | Requests delayed suspension after the application switches to the background.
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<number> | Obtains the remaining duration before the application is suspended.
This API uses a promise to return the task execution result.| -| cancelSuspendDelay(requestId: number): void | Cancels the suspension delay.| +| API | Description | +| ---------------------------------------- | ---------------------------------------- | +| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | Requests delayed suspension after the application switches to the background.
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<number> | Obtains the remaining duration before the application is suspended.
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<void> | Requests a continuous task from the system so that the application keeps running in the background.| -| 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). **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") + } +}; +``` -- GitLab