diff --git a/zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md index b7fff65f534301b064789b4e85e2a6dff604e38d..337f7f8bfb347f73f6def59e57323a61507665e0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @@ -11,7 +11,8 @@ ## 导入模块 ```ts -import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility' +import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; +import workScheduler from '@ohos.resourceschedule.workScheduler'; ``` ## 属性 @@ -40,7 +41,7 @@ onWorkStart(work: workScheduler.WorkInfo): void ```ts export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { - onWorkStart(workInfo) { + onWorkStart(workInfo: workScheduler.WorkInfo) { console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo)); } } @@ -65,7 +66,7 @@ onWorkStop(work: workScheduler.WorkInfo): void ```ts export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { - onWorkStop(workInfo) { + onWorkStop(workInfo: workScheduler.WorkInfo) { console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo)); } } diff --git a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md index ca460869b665fa549a3fca272acd283b167fd9ca..3284f0899bdf2e2f3c3a269f349c8383184a923a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -115,14 +115,14 @@ getRemainingDelayTime(requestId: number): Promise<number> **示例**: - ```js - let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); - backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId).then( res => { - console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); - }).catch( err => { - console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); - }) - ``` +```js +let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); + backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId).then((res:number) => { + console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); +}).catch((err : BusinessError) => { + console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); +}) +``` ## backgroundTaskManager.cancelSuspendDelay @@ -173,31 +173,32 @@ FA模型示例: ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; -import wantAgent from '@ohos.app.ability.wantAgent'; - -function callback(err, data) { - if (err) { - console.error("Operation startBackgroundRunning failed Cause: " + err); - } else { - console.info("Operation startBackgroundRunning succeeded"); - } +import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; +import { BusinessError } from '@ohos.base'; + +function callback(err: BusinessError, data: void) { + if (err) { + console.error("Operation startBackgroundRunning failed Cause: " + err); + } else { + console.info("Operation startBackgroundRunning succeeded"); + } } -let wantAgentInfo = { - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +let wantAgentInfo : wantAgent.WantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] }; -wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) +wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) }); ``` @@ -207,35 +208,36 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; -import wantAgent from '@ohos.app.ability.wantAgent'; - -function callback(err, data) { - if (err) { - console.error("Operation startBackgroundRunning failed Cause: " + err); - } else { - console.info("Operation startBackgroundRunning succeeded"); - } +import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; +import { BusinessError } from '@ohos.base'; + +function callback(err: BusinessError, data: void) { + if (err) { + console.error("Operation startBackgroundRunning failed Cause: " + err); + } else { + console.info("Operation startBackgroundRunning succeeded"); + } } export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - let wantAgentInfo = { - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - backgroundTaskManager.startBackgroundRunning(this.context, - backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) - }); - } + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + let wantAgentInfo : wantAgent.WantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) + }); + } }; ``` @@ -270,27 +272,28 @@ FA模型示例: ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; -import wantAgent from '@ohos.app.ability.wantAgent'; - -let wantAgentInfo = { - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; +import { BusinessError } from '@ohos.base'; + +let wantAgentInfo : wantAgent.WantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] }; -wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); +wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err: BusinessError) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); }); ``` @@ -299,31 +302,32 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; -import wantAgent from '@ohos.app.ability.wantAgent'; +import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; +import { BusinessError } from '@ohos.base'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - let wantAgentInfo = { - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - backgroundTaskManager.startBackgroundRunning(this.context, - backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - }); - } + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + let wantAgentInfo : wantAgent.WantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err: BusinessError) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); + }); + } }; ``` @@ -349,13 +353,14 @@ FA模型示例: ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base'; -function callback(err, data) { - if (err) { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - } else { - console.info("Operation stopBackgroundRunning succeeded"); - } +function callback(err: BusinessError, data: void) { + if (err) { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + } else { + console.info("Operation stopBackgroundRunning succeeded"); + } } backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), callback); @@ -367,19 +372,20 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import { BusinessError } from '@ohos.base'; -function callback(err, data) { - if (err) { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - } else { - console.info("Operation stopBackgroundRunning succeeded"); - } +function callback(err: BusinessError, data: void) { + if (err) { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + } else { + console.info("Operation stopBackgroundRunning succeeded"); + } } export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - backgroundTaskManager.stopBackgroundRunning(this.context, callback); - } + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + backgroundTaskManager.stopBackgroundRunning(this.context, callback); + } }; ``` @@ -410,11 +416,12 @@ FA模型示例: ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base'; backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); -}).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); + console.info("Operation stopBackgroundRunning succeeded"); +}).catch((err: BusinessError) => { + console.error("Operation stopBackgroundRunning failed Cause: " + err); }); ``` @@ -424,15 +431,16 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import { BusinessError } from '@ohos.base'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - }); - } + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { + console.info("Operation stopBackgroundRunning succeeded"); + }).catch((err: BusinessError) => { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + }); + } }; ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md index 0054d61a952a3b20a9e6be5bdc5b895e00c2c9b5..43ee71cf267cc6321af03b5a0b30344644924b21 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md @@ -15,9 +15,10 @@ WorkSchedulerExtensionContext可直接作为WorkSchedulerExtension的上下文 ```ts import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; +import workScheduler from '@ohos.resourceschedule.workScheduler'; class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { - onWorkStart(workInfo) { + onWorkStart(workInfo: workScheduler.WorkInfo) { let WorkSchedulerExtensionContext = this.context; // 获取WorkSchedulerExtensionContext } } diff --git a/zh-cn/application-dev/task-management/continuous-task.md b/zh-cn/application-dev/task-management/continuous-task.md index c027b5b4bb68cdb95319c94e54b66058366e8fd3..70cf3617e06d706bf782e1b2db14358b5ce5fb6a 100644 --- a/zh-cn/application-dev/task-management/continuous-task.md +++ b/zh-cn/application-dev/task-management/continuous-task.md @@ -81,8 +81,9 @@ 3. 导入模块。 ```ts - import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; - import wantAgent from '@ohos.app.ability.wantAgent'; + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; + import { BusinessError } from '@ohos.base'; ``` 4. 申请和取消长时任务。 @@ -99,10 +100,10 @@ struct Index { @State message: string = 'ContinuousTask'; // 通过getContext方法,来获取page所在的UIAbility上下文。 - private context = getContext(this); + private context: Context = getContext(this); startContinuousTask() { - let wantAgentInfo = { + let wantAgentInfo: wantAgent.wantAgentInfo = { // 点击通知后,将要执行的动作列表 wants: [ { @@ -119,30 +120,22 @@ }; // 通过wantAgent模块下getWantAgent方法获取WantAgent对象 - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(this.context, - backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { - console.info(`Succeeded in operationing startBackgroundRunning.`); - }).catch((err) => { - console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - }); - } catch (error) { - console.error(`Failed to start background running. Code is ${error.code} message is ${error.message}`); - } + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { + console.info(`Succeeded in operationing startBackgroundRunning.`); + }).catch((err: BusinessError) => { + console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); }); } stopContinuousTask() { - try { - backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { - console.info(`Succeeded in operationing stopBackgroundRunning.`); - }).catch((err) => { - console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - }); - } catch (error) { - console.error(`Failed to stop background running. Code is ${error.code} message is ${error.message}`); - } + backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { + console.info(`Succeeded in operationing stopBackgroundRunning.`); + }).catch((err: BusinessError) => { + console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); } build() { @@ -192,131 +185,129 @@ **跨设备或跨应用**申请长时任务示例代码如下: ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - - const MSG_SEND_METHOD: string = 'CallSendMsg' - - let mContext = null; - - function startContinuousTask() { - 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] - }; - - // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(mContext, - backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { - console.info(`Succeeded in operationing startBackgroundRunning.`); - }).catch((err) => { - console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - }); - } catch (err) { - console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - } - }); - } - - function stopContinuousTask() { - try { - backgroundTaskManager.stopBackgroundRunning(mContext).then(() => { - console.info(`Succeeded in operationing stopBackgroundRunning.`); - }).catch((err) => { - console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - }); - } catch (err) { - console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - } - } - - class MyParcelable { - num: number = 0; - str: String = ''; - - constructor(num, string) { - this.num = num; - this.str = string; - } - - marshalling(messageSequence) { - messageSequence.writeInt(this.num); - messageSequence.writeString(this.str); - return true; - } - - unmarshalling(messageSequence) { - this.num = messageSequence.readInt(); - this.str = messageSequence.readString(); - return true; - } - } - - function sendMsgCallback(data) { - console.info('BgTaskAbility funcCallBack is called ' + data) - let receivedData = new MyParcelable(0, '') - data.readParcelable(receivedData) - console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) - // 可以根据Caller端发送的序列化数据的str值,执行不同的方法。 - if (receivedData.str === 'start_bgtask') { - startContinuousTask() - } else if (receivedData.str === 'stop_bgtask') { - stopContinuousTask(); - } - return new MyParcelable(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') - } - }; + import UIAbility from '@ohos.app.ability.UIAbility'; + import window from '@ohos.window'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + import Want from '@ohos.app.ability.Want'; + import rpc from '@ohos.rpc'; + + const MSG_SEND_METHOD: string = 'CallSendMsg' + + let mContext: Context; + + function startContinuousTask() { + let wantAgentInfo : wantAgent.WantAgentInfo = { + // 点击通知后,将要执行的动作列表 + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", + } + ], + // 点击通知后,动作类型 + operationType: wantAgent.OperationType.START_ABILITY, + // 使用者自定义的一个私有值 + requestCode: 0, + // 点击通知后,动作执行属性 + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => { + backgroundTaskManager.startBackgroundRunning(mContext, + backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { + console.info(`Succeeded in operationing startBackgroundRunning.`); + }).catch((err: BusinessError) => { + console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); + }); + } + + function stopContinuousTask() { + backgroundTaskManager.stopBackgroundRunning(mContext).then(() => { + console.info(`Succeeded in operationing stopBackgroundRunning.`); + }).catch((err: BusinessError) => { + console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); + } + + class MyParcelable { + num: number = 0; + str: String = ''; + + constructor(num: number, string: string) { + this.num = num; + this.str = string; + } + + marshalling(messageSequence: rpc.MessageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); + return true; + } + + unmarshalling(messageSequence: rpc.MessageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); + return true; + } + } + + function sendMsgCallback(data: rpc.MessageSequence) { + console.info('BgTaskAbility funcCallBack is called ' + data); + let receivedData = new MyParcelable(0, ''); + data.readParcelable(receivedData); + console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); + // 可以根据Caller端发送的序列化数据的str值,执行不同的方法。 + if (receivedData.str === 'start_bgtask') { + startContinuousTask(); + } else if (receivedData.str === 'stop_bgtask') { + stopContinuousTask(); + } + return new MyParcelable(10, 'Callee test'); + } + + export default class BgTaskAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.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: window.WindowStage) { + console.info('[Demo] BgTaskAbility onWindowStageCreate'); + + windowStage.loadContent('pages/Index', (error, data) => { + if (error.code) { + console.error(`load content failed with error ${JSON.stringify(error)}`); + return; + } + console.info(`load content succeed with data ${JSON.stringify(data)}`); + }); + } + + onWindowStageDestroy() { + console.info('[Demo] BgTaskAbility onWindowStageDestroy'); + } + + onForeground() { + console.info('[Demo] BgTaskAbility onForeground'); + } + + onBackground() { + console.info('[Demo] BgTaskAbility onBackground'); + } + }; ``` @@ -355,119 +346,112 @@ 3. 导入模块。 ```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"; + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + import featureAbility from '@ohos.ability.featureAbility'; + import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; + import rpc from "@ohos.rpc"; + import { BusinessError } from '@ohos.base'; ``` 4. 申请和取消长时任务。在 ServiceAbility 中,调用 startBackgroundRunning() 接口和 startBackgroundRunning() 接口实现长时任务的申请和取消。 ```js - function startContinuousTask() { - 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] - }; - - // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { - console.info(`Succeeded in operationing startBackgroundRunning.`); - }).catch((err) => { - console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - }); - } catch (error) { - console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - } - }); - } - - function stopContinuousTask() { - try { - backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { - console.info(`Succeeded in operationing stopBackgroundRunning.`); - }).catch((err) => { - console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - }); - } catch (error) { - console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - } - } - - async function processAsyncJobs() { - // 此处执行具体的长时任务。 - - // 长时任务执行完,调用取消接口,释放资源。 - 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'); - // code 的具体含义用户自定义 - if (code === 1) { - // 接收到申请长时任务的请求码 - startContinuousTask(); - // 此处执行具体长时任务 - } else if (code === 2) { - // 接收到取消长时任务的请求码 - stopContinuousTask(); - } else { - console.log('ServiceAbility unknown request code'); - } - return true; - } - } - - export default { - onStart(want) { - console.info('ServiceAbility onStart'); - mMyStub = new MyStub("ServiceAbility-test"); - // 在执行长时任务前,调用申请接口。 - 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, restart, startId) { - console.info('ServiceAbility onCommand'); - } - }; + function startContinuousTask() { + let wantAgentInfo: wantAgent.WantAgentInfo = { + // 点击通知后,将要执行的动作列表 + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + // 点击通知后,动作类型 + operationType: wantAgent.OperationType.START_ABILITY, + // 使用者自定义的一个私有值 + requestCode: 0, + // 点击通知后,动作执行属性 + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { + console.info(`Succeeded in operationing startBackgroundRunning.`); + }).catch((err: BusinessError) => { + console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); + }); + } + + function stopContinuousTask() { + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { + console.info(`Succeeded in operationing stopBackgroundRunning.`); + }).catch((err: BusinessError) => { + console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); + } + + async function processAsyncJobs() { + // 此处执行具体的长时任务。 + + // 长时任务执行完,调用取消接口,释放资源。 + stopContinuousTask(); + } + + let mMyStub: MyStub; + + 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'); + // code 的具体含义用户自定义 + if (code === 1) { + // 接收到申请长时任务的请求码 + startContinuousTask(); + // 此处执行具体长时任务 + } else if (code === 2) { + // 接收到取消长时任务的请求码 + stopContinuousTask(); + } else { + console.log('ServiceAbility unknown request code'); + } + return true; + } + } + + export default { + onStart(want) { + console.info('ServiceAbility onStart'); + mMyStub = new MyStub("ServiceAbility-test"); + // 在执行长时任务前,调用申请接口。 + 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, restart, startId) { + console.info('ServiceAbility onCommand'); + } + }; ``` diff --git a/zh-cn/application-dev/task-management/work-scheduler.md b/zh-cn/application-dev/task-management/work-scheduler.md index 484f68b5b93cf0b33a2e8e9cf0f86a2c3181694f..151854ae89fdd2cfe5e25900b33e89ca72b39abe 100644 --- a/zh-cn/application-dev/task-management/work-scheduler.md +++ b/zh-cn/application-dev/task-management/work-scheduler.md @@ -121,6 +121,7 @@ WorkInfo参数用于设置应用条件,参数设置时需遵循以下规则: ```ts import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; + import workScheduler fron '@ohos.resourceschedule.workScheduler'; ``` 3. 实现WorkSchedulerExtension生命周期接口。 @@ -128,12 +129,12 @@ WorkInfo参数用于设置应用条件,参数设置时需遵循以下规则: ```ts export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { // 延迟任务开始回调 - onWorkStart(workInfo) { + onWorkStart(workInfo: workScheduler.WorkInfo) { console.info(`onWorkStart, workInfo = ${JSON.stringify(workInfo)}`); } // 延迟任务结束回调 - onWorkStop(workInfo) { + onWorkStop(workInfo: workScheduler.WorkInfo) { console.info(`onWorkStop, workInfo is ${JSON.stringify(workInfo)}`); } } @@ -173,7 +174,7 @@ WorkInfo参数用于设置应用条件,参数设置时需遵循以下规则: 2. 申请延迟任务。 ```ts - private workInfo = { + private workInfo: workScheduler.WorkInfo = { workId: 1, networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI, bundleName: 'com.example.application', @@ -183,7 +184,7 @@ WorkInfo参数用于设置应用条件,参数设置时需遵循以下规则: try { workScheduler.startWork(this.workInfo); console.info(`startWork success`); - } catch (error) { + } catch (error: BusinessError) { console.error(`startWork failed. code is ${error.code} message is ${error.message}`); } ``` @@ -191,7 +192,7 @@ WorkInfo参数用于设置应用条件,参数设置时需遵循以下规则: 3. 取消延迟任务。 ```ts - private workInfo = { + private workInfo: workScheduler.workInfo = { workId: 1, networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI, bundleName: 'com.example.application', @@ -201,7 +202,7 @@ WorkInfo参数用于设置应用条件,参数设置时需遵循以下规则: try { workScheduler.stopWork(this.workInfo); console.info(`stopWork success`); - } catch (error) { + } catch (error: BusinessError) { console.error(`stopWork failed. code is ${error.code} message is ${error.message}`); } ```