1# @ohos.backgroundTaskManager (后台任务管理) 2 3本模块提供后台任务管理能力。 4 5当应用或业务模块处于后台(无可见界面)时,如果有需要继续执行或者后续执行的业务,可基于业务类型,申请短时任务延迟挂起(Suspend)或者长时任务避免进入挂起状态。 6 7应用有不可中断且短时间能完成的任务时(如,用户在文件管理器上点击垃圾文件清理,若清理未完成时退到后台,文件管理器需要申请短时任务完成清理),可以使用短时任务机制。 8 9应用中存在用户能够直观感受到的且需要一直在后台运行的业务时(如,后台播放音乐),可以使用长时任务机制。 10 11对于系统特权应用,提供独立的能效资源申请接口。系统特权应用如果需要使用特定的系统资源,例如需要在被挂起期间仍然能够收到系统公共事件,可以使用能效资源申请接口。 12 13> **说明:** 14> - 从API Version 9 开始,该接口不再维护,推荐使用新接口[@ohos.resourceschedule.backgroundTaskManager (后台任务管理)](js-apis-resourceschedule-backgroundTaskManager.md) 15> - 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 16 17 18## 导入模块 19 20```ts 21import backgroundTaskManager from '@ohos.backgroundTaskManager'; 22``` 23 24 25## backgroundTaskManager.requestSuspendDelay 26 27requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspendInfo 28 29后台应用申请延迟挂起。 30 31延迟挂起时间一般情况下默认值为3分钟,低电量(依据系统低电量广播)时默认值为1分钟。 32 33**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 34 35**参数**: 36 37| 参数名 | 类型 | 必填 | 说明 | 38| -------- | -------------------- | ---- | ------------------------------ | 39| reason | string | 是 | 延迟挂起申请的原因。 | 40| callback | Callback<void> | 是 | 延迟即将超时的回调函数,一般在超时前6秒通过此回调通知应用。 | 41 42**返回值**: 43 44| 类型 | 说明 | 45| ------------------------------------- | --------- | 46| [DelaySuspendInfo](#delaysuspendinfo) | 返回延迟挂起信息。 | 47 48**示例**: 49 50 ```ts 51 import backgroundTaskManager from '@ohos.backgroundTaskManager'; 52 import { BusinessError } from '@ohos.base'; 53 54 let myReason = 'test requestSuspendDelay'; 55 let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { 56 console.info("Request suspension delay will time out."); 57 }) 58 59 let id = delayInfo.requestId; 60 let time = delayInfo.actualDelayTime; 61 console.info("The requestId is: " + id); 62 console.info("The actualDelayTime is: " + time); 63 ``` 64 65 66## backgroundTaskManager.getRemainingDelayTime 67 68getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void 69 70获取应用程序进入挂起状态前的剩余时间,使用callback形式返回。 71 72**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 73 74**参数**: 75 76| 参数名 | 类型 | 必填 | 说明 | 77| --------- | --------------------------- | ---- | ---------------------------------------- | 78| requestId | number | 是 | 延迟挂起的请求ID。这个值通过调用[requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay)方法获取。 | 79| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。用于返回应用程序进入挂起状态之前的剩余时间,以毫秒为单位。 | 80 81**示例**: 82 83 ```ts 84 import backgroundTaskManager from '@ohos.backgroundTaskManager'; 85 import { BusinessError } from '@ohos.base'; 86 87 let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); 88 backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId, (err: BusinessError, res: number) => { 89 if(err) { 90 console.log('callback => Operation getRemainingDelayTime failed. Cause: ' + err.code); 91 } else { 92 console.log('callback => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); 93 } 94 }) 95 ``` 96 97 98## backgroundTaskManager.getRemainingDelayTime 99 100getRemainingDelayTime(requestId: number): Promise<number> 101 102获取应用程序进入挂起状态前的剩余时间,使用Promise形式返回。 103 104**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 105 106**参数**: 107 108| 参数名 | 类型 | 必填 | 说明 | 109| --------- | ------ | ---- | ---------- | 110| requestId | number | 是 | 延迟挂起的请求ID。这个值通过调用[requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay)方法获取。 | 111 112**返回值**: 113 114| 类型 | 说明 | 115| --------------------- | ---------------------------------------- | 116| Promise<number> | 指定的Promise回调方法。返回应用程序进入挂起状态之前的剩余时间,以毫秒为单位。 | 117 118**示例**: 119 120```ts 121import backgroundTaskManager from '@ohos.backgroundTaskManager'; 122import { BusinessError } from '@ohos.base'; 123 124let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); 125 backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId).then((res:number) => { 126 console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); 127}).catch((err : BusinessError) => { 128 console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); 129}) 130``` 131 132 133## backgroundTaskManager.cancelSuspendDelay 134 135cancelSuspendDelay(requestId: number): void 136 137取消延迟挂起。 138 139**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 140 141**参数**: 142 143| 参数名 | 类型 | 必填 | 说明 | 144| --------- | ------ | ---- | ---------- | 145| requestId | number | 是 | 延迟挂起的请求ID。这个值通过调用[requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay)方法获取。 | 146 147**示例**: 148 149 ```ts 150 let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); 151 backgroundTaskManager.cancelSuspendDelay(delayInfo.requestId); 152 ``` 153 154 155## backgroundTaskManager.startBackgroundRunning<sup>8+</sup> 156 157startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void 158 159向系统申请长时任务,使用callback形式返回结果。 160 161**需要权限:** ohos.permission.KEEP_BACKGROUND_RUNNING 162 163**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 164 165**参数**: 166 167| 参数名 | 类型 | 必填 | 说明 | 168| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | 169| context | Context | 是 | 应用运行的上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | 170| bgMode | [BackgroundMode](#backgroundmode8) | 是 | 向系统申请的后台模式。 | 171| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 通知参数,用于指定长时任务通知点击后跳转的界面。 | 172| callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果。 | 173 174**示例**: 175 176FA模型示例: 177 178```js 179import backgroundTaskManager from '@ohos.backgroundTaskManager'; 180import featureAbility from '@ohos.ability.featureAbility'; 181import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; 182import { BusinessError } from '@ohos.base'; 183 184function callback(err: BusinessError, data: void) { 185 if (err) { 186 console.error("Operation startBackgroundRunning failed Cause: " + err); 187 } else { 188 console.info("Operation startBackgroundRunning succeeded"); 189 } 190} 191 192let wantAgentInfo : wantAgent.WantAgentInfo = { 193 wants: [ 194 { 195 bundleName: "com.example.myapplication", 196 abilityName: "EntryAbility" 197 } 198 ], 199 operationType: wantAgent.OperationType.START_ABILITY, 200 requestCode: 0, 201 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 202}; 203 204wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => { 205 backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), 206 backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) 207}); 208 209``` 210 211Stage模型示例: 212 213```ts 214import UIAbility from '@ohos.app.ability.UIAbility'; 215import backgroundTaskManager from '@ohos.backgroundTaskManager'; 216import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; 217import Want from '@ohos.app.ability.Want'; 218import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 219import { BusinessError } from '@ohos.base'; 220 221function callback(err: BusinessError, data: void) { 222 if (err) { 223 console.error("Operation startBackgroundRunning failed Cause: " + err); 224 } else { 225 console.info("Operation startBackgroundRunning succeeded"); 226 } 227} 228 229export default class EntryAbility extends UIAbility { 230 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 231 let wantAgentInfo : wantAgent.WantAgentInfo = { 232 wants: [ 233 { 234 bundleName: "com.example.myapplication", 235 abilityName: "EntryAbility" 236 } 237 ], 238 operationType: wantAgent.OperationType.START_ABILITY, 239 requestCode: 0, 240 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 241 }; 242 243 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => { 244 backgroundTaskManager.startBackgroundRunning(this.context, 245 backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) 246 }); 247 } 248}; 249``` 250 251## backgroundTaskManager.startBackgroundRunning<sup>8+</sup> 252 253startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void> 254 255向系统申请长时任务,使用promise形式返回结果。 256 257**需要权限:** ohos.permission.KEEP_BACKGROUND_RUNNING 258 259**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 260 261**参数**: 262 263| 参数名 | 类型 | 必填 | 说明 | 264| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | 265| context | Context | 是 | 应用运行的上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | 266| bgMode | [BackgroundMode](#backgroundmode8) | 是 | 向系统申请的后台模式。 | 267| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 通知参数,用于指定长时任务通知点击跳转的界面。 | 268 269**返回值**: 270 271| 类型 | 说明 | 272| -------------- | ---------------- | 273| Promise\<void> | 使用Promise形式返回结果。 | 274 275**示例**: 276 277FA模型示例(需使用js代码开发): 278 279```js 280import backgroundTaskManager from '@ohos.backgroundTaskManager'; 281import featureAbility from '@ohos.ability.featureAbility'; 282import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; 283import { BusinessError } from '@ohos.base'; 284 285let wantAgentInfo : wantAgent.WantAgentInfo = { 286 wants: [ 287 { 288 bundleName: "com.example.myapplication", 289 abilityName: "EntryAbility" 290 } 291 ], 292 operationType: wantAgent.OperationType.START_ABILITY, 293 requestCode: 0, 294 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 295}; 296 297wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { 298 backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), 299 backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { 300 console.info("Operation startBackgroundRunning succeeded"); 301 }).catch((err: BusinessError) => { 302 console.error("Operation startBackgroundRunning failed Cause: " + err); 303 }); 304}); 305``` 306 307Stage模型示例: 308 309```ts 310import UIAbility from '@ohos.app.ability.UIAbility'; 311import backgroundTaskManager from '@ohos.backgroundTaskManager'; 312import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; 313import Want from '@ohos.app.ability.Want'; 314import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 315import { BusinessError } from '@ohos.base'; 316 317export default class EntryAbility extends UIAbility { 318 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 319 let wantAgentInfo : wantAgent.WantAgentInfo = { 320 wants: [ 321 { 322 bundleName: "com.example.myapplication", 323 abilityName: "EntryAbility" 324 } 325 ], 326 operationType: wantAgent.OperationType.START_ABILITY, 327 requestCode: 0, 328 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 329 }; 330 331 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => { 332 backgroundTaskManager.startBackgroundRunning(this.context, 333 backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { 334 console.info("Operation startBackgroundRunning succeeded"); 335 }).catch((err: BusinessError) => { 336 console.error("Operation startBackgroundRunning failed Cause: " + err); 337 }); 338 }); 339 } 340}; 341``` 342 343## backgroundTaskManager.stopBackgroundRunning<sup>8+</sup> 344 345stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void 346 347向系统申请取消长时任务,使用callback形式返回结果。 348 349**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 350 351**参数**: 352 353| 参数名 | 类型 | 必填 | 说明 | 354| -------- | ------------------------- | ---- | ---------------------------------------- | 355| context | Context | 是 | 应用运行的上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | 356| callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果。 | 357 358**示例**: 359 360FA模型示例(需使用js代码开发): 361 362```js 363import backgroundTaskManager from '@ohos.backgroundTaskManager'; 364import featureAbility from '@ohos.ability.featureAbility'; 365import { BusinessError } from '@ohos.base'; 366 367function callback(err: BusinessError, data: void) { 368 if (err) { 369 console.error("Operation stopBackgroundRunning failed Cause: " + err); 370 } else { 371 console.info("Operation stopBackgroundRunning succeeded"); 372 } 373} 374 375backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), callback); 376 377``` 378 379Stage模型示例: 380 381```ts 382import UIAbility from '@ohos.app.ability.UIAbility'; 383import backgroundTaskManager from '@ohos.backgroundTaskManager'; 384import Want from '@ohos.app.ability.Want'; 385import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 386import { BusinessError } from '@ohos.base'; 387 388function callback(err: BusinessError, data: void) { 389 if (err) { 390 console.error("Operation stopBackgroundRunning failed Cause: " + err); 391 } else { 392 console.info("Operation stopBackgroundRunning succeeded"); 393 } 394} 395 396export default class EntryAbility extends UIAbility { 397 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 398 backgroundTaskManager.stopBackgroundRunning(this.context, callback); 399 } 400}; 401``` 402 403## backgroundTaskManager.stopBackgroundRunning<sup>8+</sup> 404 405stopBackgroundRunning(context: Context): Promise<void> 406 407向系统申请取消长时任务,使用promise形式返回结果。 408 409**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 410 411**参数**: 412 413| 参数名 | 类型 | 必填 | 说明 | 414| ------- | ------- | ---- | ---------------------------------------- | 415| context | Context | 是 | 应用运行的上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | 416 417**返回值**: 418 419| 类型 | 说明 | 420| -------------- | ---------------- | 421| Promise\<void> | 使用Promise形式返回结果。 | 422 423**示例**: 424 425FA模型示例: 426 427```js 428import backgroundTaskManager from '@ohos.backgroundTaskManager'; 429import featureAbility from '@ohos.ability.featureAbility'; 430import { BusinessError } from '@ohos.base'; 431 432backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { 433 console.info("Operation stopBackgroundRunning succeeded"); 434}).catch((err: BusinessError) => { 435 console.error("Operation stopBackgroundRunning failed Cause: " + err); 436}); 437 438``` 439 440Stage模型示例: 441 442```ts 443import UIAbility from '@ohos.app.ability.UIAbility'; 444import backgroundTaskManager from '@ohos.backgroundTaskManager'; 445import Want from '@ohos.app.ability.Want'; 446import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 447import { BusinessError } from '@ohos.base'; 448 449export default class EntryAbility extends UIAbility { 450 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 451 backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { 452 console.info("Operation stopBackgroundRunning succeeded"); 453 }).catch((err: BusinessError) => { 454 console.error("Operation stopBackgroundRunning failed Cause: " + err); 455 }); 456 } 457}; 458``` 459 460## DelaySuspendInfo 461 462延迟挂起信息。 463 464**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 465 466| 名称 | 类型 | 必填 | 说明 | 467| --------------- | ------ | ---- | ---------------------------------------- | 468| requestId | number | 是 | 延迟挂起的请求ID。 | 469| actualDelayTime | number | 是 | 应用的实际挂起延迟时间,以毫秒为单位。<br/>一般情况下默认值为180000,低电量(依据系统低电量广播)时默认值为60000。 | 470 471 472## BackgroundMode<sup>8+</sup> 473 474**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 475 476| 名称 | 值 | 说明 | 477| ----------------------- | ---- | --------------------- | 478| DATA_TRANSFER | 1 | 数据传输。 | 479| AUDIO_PLAYBACK | 2 | 音频播放。 | 480| AUDIO_RECORDING | 3 | 录音。 | 481| LOCATION | 4 | 定位导航。 | 482| BLUETOOTH_INTERACTION | 5 | 蓝牙相关。 | 483| MULTI_DEVICE_CONNECTION | 6 | 多设备互联。 | 484| WIFI_INTERACTION | 7 | WLAN相关<br />此接口为系统接口。 | 485| VOIP | 8 | 音视频通话<br />此接口为系统接口。 | 486| TASK_KEEPING | 9 | 计算任务(仅在特定设备生效)。 | 487