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