diff --git a/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md index a22f7b48a977066e085da4b9ddfcdeb24f21463f..33555ada83df3e20766793df3208f250ac612a00 100644 --- a/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @@ -16,6 +16,14 @@ When developing an application, you can override the APIs of this module and add import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility' ``` +## Attributes + +**System capability**: SystemCapability.ResourceSchedule.WorkScheduler + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| context | [WorkSchedulerExtensionContext](js-apis-inner-application-WorkSchedulerExtensionContext.md) | Yes| No| Context of the **WorkSchedulerExtension**. This context is inherited from **ExtensionContext**.| + ## WorkSchedulerExtensionAbility.onWorkStart onWorkStart(work: workScheduler.WorkInfo): void diff --git a/en/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md new file mode 100644 index 0000000000000000000000000000000000000000..ff2ca7a3df236c2bf50ab883de28cae0b0599259 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md @@ -0,0 +1,24 @@ +# WorkSchedulerExtensionContext + +The **WorkSchedulerExtensionContext** module, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md), is the context environment of the WorkSchedulerExtensionAbility. + +This module provides APIs for accessing the resources of a WorkSchedulerExtensionAbility. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Usage + +The context is obtained through a WorkSchedulerExtensionAbility child class instance. + +```ts +import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; + +class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { + onWorkStart(workInfo) { + let WorkSchedulerExtensionContext = this.context; // Obtain the WorkSchedulerExtensionContext. + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md index 0e7ad7e7c38f32e85af6ab3504252da38afb32eb..eb4c8609bbec28c19d441f065d94c716e13c2e31 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @@ -430,7 +430,7 @@ Provides detailed information about the task. For details about the constraints | isPersisted | boolean | No | Whether to enable persistent storage for the task. | | isDeepIdle | boolean | No | Whether the device needs to enter the idle state. | | idleWaitTime | number | No | Time to wait in the idle state. | -| parameters | {[key: string]: any} | No | Carried parameters. | +| parameters | {[key: string]: number | string | boolean} | No | Carried parameters. | ## NetworkType Enumerates the network types that can trigger the task. diff --git a/en/application-dev/task-management/Readme-EN.md b/en/application-dev/task-management/Readme-EN.md index 8f5c8d904521a8188079239092ffd5b88a58b955..b18e933695fa7e156440feafd5bfc7719b10b59e 100644 --- a/en/application-dev/task-management/Readme-EN.md +++ b/en/application-dev/task-management/Readme-EN.md @@ -1,4 +1,4 @@ -# Task Management +# Background Task Management - Background Task - [Background Task Management Overview](background-task-overview.md) @@ -8,6 +8,6 @@ - [WorkSchedulerExtensionAbility Development](workscheduler-extensionability.md) - [Efficiency Resource Request Development](efficiency-resources-apply-dev-guide.md) -- Agent-Powered Scheduled Reminder +- Agent-Powered Reminder - [Agent-Powered Reminder Overview](reminder-agent-overview.md) - [Agent-Powered Reminder Development](reminder-agent-development.md) \ No newline at end of file diff --git a/en/application-dev/task-management/background-task-overview.md b/en/application-dev/task-management/background-task-overview.md index fcef6d4c6012386d5705efb59a247ac01425dd75..6f3252f0ad09e23b263590a51ba52749d357d526 100644 --- a/en/application-dev/task-management/background-task-overview.md +++ b/en/application-dev/task-management/background-task-overview.md @@ -41,7 +41,7 @@ Adhere to the following constraints and rules when using transient tasks: - **When to cancel**: The application shall proactively cancel the request when the transient task is complete, rather than waiting for a system callback. Otherwise, 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.) +- **Quota mechanism**: To prevent abuse of the keepalive, each application has a certain quota every day (dynamically adjusted based on user habits). The default quota for a single day is 10 minutes, and the maximum quota for each request is 3 minutes. 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. @@ -58,7 +58,7 @@ OpenHarmony provides 9 background modes for services that require continuous tas | 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. | - | +| multiDeviceConnection | Multi-device application collaboration | 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 | Effective only for specific devices | diff --git a/en/application-dev/task-management/continuous-task-dev-guide.md b/en/application-dev/task-management/continuous-task-dev-guide.md index b301ee707bf62ce6cf773be2b744d905e807da42..e48995f1fc48dd652a132b6b8f04dbaeac7a00c0 100644 --- a/en/application-dev/task-management/continuous-task-dev-guide.md +++ b/en/application-dev/task-management/continuous-task-dev-guide.md @@ -38,398 +38,398 @@ For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-app-a For details about the stage model, see [Stage Model Development Overview](../application-models/stage-model-development-overview.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. - -``` -"module": { - "abilities": [ - { - "backgroundModes": [ - "dataTransfer", - "location" - ], // Background mode - } - ], - "requestPermissions": [ - { - "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission - } - ] -} -``` +1. Configure the continuous task permission **ohos.permission.KEEP_BACKGROUND_RUNNING** in the **module.json5** file, and declare the corresponding background mode type for the ability that needs to use the task. + + ``` + "module": { + "abilities": [ + { + "backgroundModes": [ + "dataTransfer", + "location" + ], // Background mode + } + ], + "requestPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission + } + ] + } + ``` 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). -```ts -import wantAgent from '@ohos.app.ability.wantAgent'; -import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; - -@Entry -@Component -struct Index { - @State message: string = 'test' - // Use getContext to obtain the context of the Page ability. - private context: any = getContext(this) - - startContinuousTask() { - let wantAgentInfo = { - // List of operations to be executed after the notification is clicked. - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", - } - ], - // 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. - try { - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(this.context, - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - }); - } catch (error) { - console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); - } - } - - stopContinuousTask() { - try { - backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - }); - } catch (error) { - console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - } - - build() { - Row() { - Column() { - Text("Index") - .fontSize(50) - .fontWeight(FontWeight.Bold) - - Button() { Text('Request continuous task').fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) - .margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40) - .onClick(() => { - // Request a continuous task by clicking a button. - this.startContinuousTask(); - - // Execute the continuous task logic, for example, music playback. - }) - - Button() {Text('Cancel continuous task') .fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) - .margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40) - .onClick(() => { - // Stop the continuous task. - - // Cancel the continuous task by clicking a button. - this.stopContinuousTask(); - }) - } - .width('100%') - } - .height('100%') - } -} -``` + ```ts + import wantAgent from '@ohos.app.ability.wantAgent'; + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + + @Entry + @Component + struct Index { + @State message: string = 'test' + // Use getContext to obtain the context of the Page ability. + private context: any = getContext(this) + + startContinuousTask() { + let wantAgentInfo = { + // List of operations to be executed after the notification is clicked. + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", + } + ], + // 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. + try { + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); + } catch (error) { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + }); + } catch (error) { + console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); + } + } + + stopContinuousTask() { + try { + backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { + console.info("Operation stopBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + }); + } catch (error) { + console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + } + + build() { + Row() { + Column() { + Text("Index") + .fontSize(50) + .fontWeight(FontWeight.Bold) + + Button() { Text('Request continuous task').fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) + .margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40) + .onClick(() => { + // Request a continuous task by clicking a button. + this.startContinuousTask(); + + // Execute the continuous task logic, for example, music playback. + }) + + Button() {Text('Cancel continuous task') .fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) + .margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40) + .onClick(() => { + // Stop the continuous task. + + // Cancel the continuous task by clicking a button. + this.stopContinuousTask(); + }) + } + .width('100%') + } + .height('100%') + } + } + ``` 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). -```ts -import UIAbility from '@ohos.app.ability.UIAbility'; -import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; -import wantAgent from '@ohos.app.ability.wantAgent'; - -const MSG_SEND_METHOD: string = 'CallSendMsg'; - -let mContext = null; - -function startContinuousTask() { - let wantAgentInfo = { - // List of operations to be executed after the notification is clicked. - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", - } - ], - // 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. - try { - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(mContext, - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((error) => { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - }); - } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - }); - } catch (error) { - console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); - } -} - -function stopContinuousTask() { - try { - backgroundTaskManager.stopBackgroundRunning(mContext).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((error) => { - console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - }); - } catch (error) { - console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } -} - -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}]`) - // You can execute different methods based on the str value in the sequenceable data sent by the caller. - if (receivedData.str === 'start_bgtask') { - startContinuousTask() - } else if (receivedData.str === 'stop_bgtask') { - stopContinuousTask(); - } - return new MySequenceable(10, "Callee test"); -} - -export default class BgTaskAbility extends UIAbility { - 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/index").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") - } -}; -``` + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + import wantAgent from '@ohos.app.ability.wantAgent'; + + const MSG_SEND_METHOD: string = 'CallSendMsg'; + + let mContext = null; + + function startContinuousTask() { + let wantAgentInfo = { + // List of operations to be executed after the notification is clicked. + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", + } + ], + // 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. + try { + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(mContext, + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((error) => { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + }); + } catch (error) { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + }); + } catch (error) { + console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); + } + } + + function stopContinuousTask() { + try { + backgroundTaskManager.stopBackgroundRunning(mContext).then(() => { + console.info("Operation stopBackgroundRunning succeeded"); + }).catch((error) => { + console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + }); + } catch (error) { + console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + } + + 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}]`) + // You can execute different methods based on the str value in the sequenceable data sent by the caller. + if (receivedData.str === 'start_bgtask') { + startContinuousTask() + } else if (receivedData.str === 'stop_bgtask') { + stopContinuousTask(); + } + return new MySequenceable(10, "Callee test"); + } + + export default class BgTaskAbility extends UIAbility { + 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/index").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") + } + }; + ``` ### Development in the FA Model 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**. - -```json -"module": { - "package": "com.example.myapplication", - "abilities": [ - { - "backgroundModes": [ - "dataTransfer", - "location" - ], // Background mode - "type": "service" // The ability type is service. - } - ], - "reqPermissions": [ - { - "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission - } - ] -} -``` - -2. Call the APIs for requesting and canceling a continuous task in the Service ability. - -```js -import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; -import featureAbility from '@ohos.ability.featureAbility'; -import wantAgent from '@ohos.app.ability.wantAgent'; -import rpc from "@ohos.rpc"; - -function startContinuousTask() { - let wantAgentInfo = { - // List of operations to be executed after the notification is clicked. - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - } - ], - // 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. - try { - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - }); - } catch (error) { - console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); - } -} - -function stopContinuousTask() { - try { - backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - }); - } catch (error) { - console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } -} - -async function processAsyncJobs() { - // Execute the continuous task. - - // After the continuous task is complete, call the API to release resources. - stopContinuousTask(); -} - -let mMyStub; - -class MyStub extends rpc.RemoteObject { - constructor(des) { - if (typeof des === 'string') { - super(des); - } else { - return null; - } - } - onRemoteRequest(code, data, reply, option) { - console.log('ServiceAbility onRemoteRequest called'); - // The meaning of code is user-defined. - if (code === 1) { - // Receive the request code for requesting a continuous task. - startContinuousTask(); - // Execute the continuous task. - } else if (code === 2) { - // Receive the request code for canceling the continuous task. - stopContinuousTask(); - } else { - console.log('ServiceAbility unknown request code'); - } - return true; - } -} - -export default { - onStart() { - console.info('ServiceAbility onStart'); - mMyStub = new MyStub("ServiceAbility-test"); - // Call the API to start the task. - startContinuousTask(); - processAsyncJobs(); - }, - onStop() { - console.info('ServiceAbility onStop'); - }, - onConnect(want) { - console.info('ServiceAbility onConnect'); - return mMyStub; - }, - onReconnect(want) { - console.info('ServiceAbility onReconnect'); - }, - onDisconnect() { - console.info('ServiceAbility onDisconnect'); - }, - onCommand(want, startId) { - console.info('ServiceAbility onCommand'); - } -}; -``` +If an application does not need to interact with a continuous task in the background, you can use **startAbility()** to start the ServiceAbility. In the **onStart** callback of the ServiceAbility, call **startBackgroundRunning()** to declare that the ServiceAbility 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 ServiceAbility. After obtaining the proxy of the ServiceAbility, the application can communicate with the ServiceAbility and control the request and cancellation of continuous tasks. + +1. Configure the continuous task permission **ohos.permission.KEEP_BACKGROUND_RUNNING** in the **config.json** file, and declare the corresponding background mode type for the ServiceAbility that needs to use the task. + + ```json + "module": { + "package": "com.example.myapplication", + "abilities": [ + { + "backgroundModes": [ + "dataTransfer", + "location" + ], // Background mode + "type": "service" // The ability type is Service. + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission + } + ] + } + ``` + +2. Call the APIs for requesting and canceling a continuous task in the ServiceAbility. + + ```js + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + import featureAbility from '@ohos.ability.featureAbility'; + import wantAgent from '@ohos.app.ability.wantAgent'; + import rpc from "@ohos.rpc"; + + function startContinuousTask() { + let wantAgentInfo = { + // List of operations to be executed after the notification is clicked. + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" + } + ], + // 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. + try { + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); + } catch (error) { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + }); + } catch (error) { + console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); + } + } + + function stopContinuousTask() { + try { + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { + console.info("Operation stopBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + }); + } catch (error) { + console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + } + + async function processAsyncJobs() { + // Execute the continuous task. + + // After the continuous task is complete, call the API to release resources. + stopContinuousTask(); + } + + let mMyStub; + + class MyStub extends rpc.RemoteObject { + constructor(des) { + if (typeof des === 'string') { + super(des); + } else { + return null; + } + } + onRemoteRequest(code, data, reply, option) { + console.log('ServiceAbility onRemoteRequest called'); + // The meaning of code is user-defined. + if (code === 1) { + // Receive the request code for requesting a continuous task. + startContinuousTask(); + // Execute the continuous task. + } else if (code === 2) { + // Receive the request code for canceling the continuous task. + stopContinuousTask(); + } else { + console.log('ServiceAbility unknown request code'); + } + return true; + } + } + + export default { + onStart() { + console.info('ServiceAbility onStart'); + mMyStub = new MyStub("ServiceAbility-test"); + // Call the API to start the task. + startContinuousTask(); + processAsyncJobs(); + }, + onStop() { + console.info('ServiceAbility onStop'); + }, + onConnect(want) { + console.info('ServiceAbility onConnect'); + return mMyStub; + }, + onReconnect(want) { + console.info('ServiceAbility onReconnect'); + }, + onDisconnect() { + console.info('ServiceAbility onDisconnect'); + }, + onCommand(want, startId) { + console.info('ServiceAbility onCommand'); + } + }; + ``` \ No newline at end of file diff --git a/en/application-dev/task-management/efficiency-resources-apply-dev-guide.md b/en/application-dev/task-management/efficiency-resources-apply-dev-guide.md index 3cdcd3ca61439fb42ff61184492332412fc77966..ec3399039a4d1aedfcce6b43c1b3187605b06dee 100644 --- a/en/application-dev/task-management/efficiency-resources-apply-dev-guide.md +++ b/en/application-dev/task-management/efficiency-resources-apply-dev-guide.md @@ -6,6 +6,9 @@ To further balance power consumption overhead of the system, privileged system a To upgrade your application as a privileged application, you must evaluate your service requirements and submit a request to the application center. The application center will determine whether to accept the request based on the conditions. +## Constraints +Only system applications can request efficiency resources. + ## Available APIs **Table 1** Main APIs for efficiency resources @@ -22,48 +25,48 @@ To upgrade your application as a privileged application, you must evaluate your 2. When the task is complete, release the resources in time. You can choose whether to release some or all resources. -```js -import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; - -// Request efficiency resources. -let request = { - resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT | - backgroundTaskManager.ResourceType.TIMER, - isApply: true, - timeOut: 0, - reason: "apply", - isPersist: true, - isProcess: true, -}; - -let res; -try { - res = backgroundTaskManager.applyEfficiencyResources(request); - console.info("the result of request is: " + res); -} catch (error) { - console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`); -} - -// Release some efficiency resources. -request = { - resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT, - isApply: false, - timeOut: 0, - reason: "reset", - isPersist: true, - isProcess: true, -}; -try { - res = backgroundTaskManager.applyEfficiencyResources(request); - console.info("the result of request is: " + res); -} catch (error) { - console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`); -} - -// Release all efficiency resources. -try { - backgroundTaskManager.resetAllEfficiencyResources(); -} catch (error) { - console.error(`Operation resetAllEfficiencyResources failed. code is ${error.code} message is ${error.message}`); -} -``` + ```js + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + + // Request efficiency resources. + let request = { + resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT | + backgroundTaskManager.ResourceType.TIMER, + isApply: true, + timeOut: 0, + reason: "apply", + isPersist: true, + isProcess: true, + }; + + let res; + try { + res = backgroundTaskManager.applyEfficiencyResources(request); + console.info("the result of request is: " + res); + } catch (error) { + console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`); + } + + // Release some efficiency resources. + request = { + resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT, + isApply: false, + timeOut: 0, + reason: "reset", + isPersist: true, + isProcess: true, + }; + try { + res = backgroundTaskManager.applyEfficiencyResources(request); + console.info("the result of request is: " + res); + } catch (error) { + console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`); + } + + // Release all efficiency resources. + try { + backgroundTaskManager.resetAllEfficiencyResources(); + } catch (error) { + console.error(`Operation resetAllEfficiencyResources failed. code is ${error.code} message is ${error.message}`); + } + ``` \ No newline at end of file diff --git a/en/application-dev/task-management/work-scheduler-dev-guide.md b/en/application-dev/task-management/work-scheduler-dev-guide.md index 845423ee6fa93a39d5ac93cbd8856f0ec0e49c23..3e5bed0e6bb48c54eecef75694f2419b31600116 100644 --- a/en/application-dev/task-management/work-scheduler-dev-guide.md +++ b/en/application-dev/task-management/work-scheduler-dev-guide.md @@ -2,7 +2,8 @@ ## When to Use -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). +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 @@ -38,7 +39,7 @@ storageRequest| [StorageRequest](../reference/apis/js-apis-resourceschedule-work isRepeat| boolean |Whether the task is repeated. repeatCycleTime| number |Repeat interval. repeatCount | number|Number of repeat times. -parameters | {[key: string]: any} |Carried parameters. +parameters | {[key: string]: number | string | boolean} |Carried parameters. **Table 3** Work Scheduler callbacks @@ -64,135 +65,134 @@ onWorkStop(work: WorkInfo): void | Called when the Work Scheduler task stops. 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). -```ts -import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; - -export default class MyExtension extends WorkSchedulerExtensionAbility { - onWorkStart(workInfo) { - console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo)); - } - onWorkStop(workInfo) { - console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo)); - } -} -``` + ```ts + import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; + + export default class MyExtension extends WorkSchedulerExtensionAbility { + onWorkStart(workInfo) { + console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo)); + } + onWorkStop(workInfo) { + console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo)); + } + } + ``` 3. Start a Work Scheduler task. -```ts -import workScheduler from '@ohos.resourceschedule.workScheduler'; + ```ts + import workScheduler from '@ohos.resourceschedule.workScheduler'; -let workInfo = { - workId: 1, - batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, - isRepeat: false, - isPersisted: true, - bundleName: "com.example.myapplication", - abilityName: "MyExtension", - parameters: { - mykey0: 1, - mykey1: "string value", - mykey2: true, - mykey3: 1.5 - } -} -try{ - workScheduler.startWork(workInfo); - console.info('workschedulerLog startWork success'); -} catch (error) { - console.error(`workschedulerLog startwork failed. code is ${error.code} message is ${error.message}`); -} -``` + let workInfo = { + workId: 1, + batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, + isRepeat: false, + isPersisted: true, + bundleName: "com.example.myapplication", + abilityName: "MyExtension", + parameters: { + mykey0: 1, + mykey1: "string value", + mykey2: true, + mykey3: 1.5 + } + } + try{ + workScheduler.startWork(workInfo); + console.info('workschedulerLog startWork success'); + } catch (error) { + console.error(`workschedulerLog startwork failed. code is ${error.code} message is ${error.message}`); + } + ``` 4. Stop the Work Scheduler task. -```ts -import workScheduler from '@ohos.resourceschedule.workScheduler'; - -let workInfo = { - workId: 1, - batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, - isRepeat: false, - isPersisted: true, - bundleName: "com.example.myapplication", - abilityName: "MyExtension", - parameters: { - mykey0: 1, - mykey1: "string value", - mykey2: true, - mykey3: 1.5 - } -} -try{ - workScheduler.stopWork(workInfo, false); - console.info('workschedulerLog stopWork success'); -} catch (error) { - console.error(`workschedulerLog stopWork failed. code is ${error.code} message is ${error.message}`); -} -``` + ```ts + import workScheduler from '@ohos.resourceschedule.workScheduler'; + + let workInfo = { + workId: 1, + batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, + isRepeat: false, + isPersisted: true, + bundleName: "com.example.myapplication", + abilityName: "MyExtension", + parameters: { + mykey0: 1, + mykey1: "string value", + mykey2: true, + mykey3: 1.5 + } + } + try{ + workScheduler.stopWork(workInfo, false); + console.info('workschedulerLog stopWork success'); + } catch (error) { + console.error(`workschedulerLog stopWork failed. code is ${error.code} message is ${error.message}`); + } + + ``` 5. Obtain a specified Work Scheduler task. -```ts -try{ - workScheduler.getWorkStatus(50, (error, res) => { - if (error) { - console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); - } else { - for (let item in res) { - console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); - } - } - }); -} catch (error) { - console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); -} -``` - + ```ts + try{ + workScheduler.getWorkStatus(50, (error, res) => { + if (error) { + console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); + } else { + for (let item in res) { + console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); + } + } + }); + } catch (error) { + console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); + } + ``` 6. Obtain all the Work Scheduler tasks. -```ts -try{ - workScheduler.obtainAllWorks((error, res) =>{ - if (error) { - console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); - } else { - console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); - } - }); -} catch (error) { - console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); -} -``` + ```ts + try{ + workScheduler.obtainAllWorks((error, res) =>{ + if (error) { + console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); + } else { + console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); + } + }); + } catch (error) { + console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); + } + ``` 7. Stop and clear all the Work Scheduler tasks. -```ts -try{ - workScheduler.stopAndClearWorks(); - console.info(`workschedulerLog stopAndClearWorks success`); -} catch (error) { - console.error(`workschedulerLog stopAndClearWorks failed. code is ${error.code} message is ${error.message}`); -} -``` + ```ts + try{ + workScheduler.stopAndClearWorks(); + console.info(`workschedulerLog stopAndClearWorks success`); + } catch (error) { + console.error(`workschedulerLog stopAndClearWorks failed. code is ${error.code} message is ${error.message}`); + } + ``` 8. Check whether the last execution of a specified Work Scheduler task has timed out. -```ts -try{ - workScheduler.isLastWorkTimeOut(500, (error, res) =>{ - if (error) { - onsole.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); - } else { - console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); - } - }); -} catch (error) { - console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); -} -``` - + ```ts + try{ + workScheduler.isLastWorkTimeOut(500, (error, res) =>{ + if (error) { + onsole.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); + } else { + console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); + } + }); + } catch (error) { + console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); + } + ``` diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.7/changelog-resourceschedule.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.7/changelog-resourceschedule.md new file mode 100644 index 0000000000000000000000000000000000000000..283f2796178e294f68f755ea2570f7cc1a24a634 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.7/changelog-resourceschedule.md @@ -0,0 +1,21 @@ +# Resource Scheduler Subsystem Changelog + +## cl.resourceschedule.workScheduler +The data type of the **parameters** attribute value is changed. Specifically, the number, string, and boolean types are supported, but the any type is not. + +**Change Impact** + +For applications developed based on OpenHarmony3.2.10.7 and later SDK versions, the **parameters** attribute value can use the number, string, and boolean types only. If it uses the any type, a compilation error is reported. + +**Key API/Component Changes** + +The **parameters** attribute in @ohos.resourceschedule.workScheduler.d.ts is changed. + +| Class| API Type| Statement Before the Change| Statement After the Change| +| -- | -- | -- | -- | +| workScheduler.WorkInfo | field | parameters?: {[key: string]: any} | parameters?: {[key: string]: number | string | boolean} | + + +**Adaptation Guide** + +The **parameters** attribute uses the {[key: string]: number | string | boolean} data type. diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.5.1/changelog-resourceschedule.md b/en/release-notes/changelogs/OpenHarmony_4.0.5.1/changelog-resourceschedule.md new file mode 100644 index 0000000000000000000000000000000000000000..225ac70d1f4e080f5d83f0bcb768a9afbbc03e1f --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.5.1/changelog-resourceschedule.md @@ -0,0 +1,32 @@ +# Resource Scheduler Subsystem Changelog + +## cl.resourceschedule.workScheduler + +The WorkSchedulerExtensionAbility provides a default WorkSchedulerExtensionContext. + +**Change Impact** + +Applications developed based on OpenHarmony4.0.5.1 and later SDK versions can use the default context attribute as the context environment of a WorkSchedulerExtension. + +**Key API/Component Changes** + +The context attribute is added to **@ohos.WorkSchedulerExtensionAbility.d.ts**. The **application/WorkSchedulerExtensionContext.d.ts** file is added, which is inherited from ExtensionContext. + +| Module| Class| Method/Attribute/Enum/Constant| Change Type| +| -- | -- | -- | -- | +| @ohos.WorkSchedulerExtensionAbility.d.ts | WorkSchedulerExtensionAbility | context: WorkSchedulerExtensionContext; | Added| +| application/WorkSchedulerExtensionContext.d.ts | WorkSchedulerExtensionContext | - | Added| + +**Adaptation Guide** + +The context is obtained through a WorkSchedulerExtensionAbility child class instance. + +```ts +import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; + +class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { + onWorkStart(workInfo) { + let WorkSchedulerExtensionContext = this.context; // Obtain the WorkSchedulerExtensionContext. + } +} +```