1# @ohos.resourceschedule.backgroundTaskManager (Background Task Management) 2 3<!--Kit: Background Tasks Kit--> 4<!--Subsystem: ResourceSchedule--> 5<!--Owner: @cheng-shichang--> 6<!--Designer: @zhouben25--> 7<!--Tester: @fenglili18--> 8<!--Adviser: @Brilliantry_Rui--> 9 10The **backgroundTaskManager** module provides APIs to request background tasks. You can use the APIs to request transient tasks, continuous tasks, or efficiency resources to prevent the application process from being terminated or suspended when your application is switched to the background. 11 12> **NOTE** 13> 14> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. 15 16 17## Modules to Import 18 19```ts 20import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 21``` 22 23## backgroundTaskManager.requestSuspendDelay 24 25requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspendInfo 26 27Requests a transient task. 28 29> **NOTE** 30> 31> For details about the constraints on requesting and using a transient task, see [Transient Task (ArkTS)](../../task-management/transient-task.md#constraints). 32 33**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 34 35**Parameters** 36 37| Name | Type | Mandatory | Description | 38| -------- | -------------------- | ---- | ------------------------------ | 39| reason | string | Yes | Reason for requesting the transient task. | 40| callback | Callback<void> | Yes | Callback used to notify the application that the transient task is about to time out. Generally, the callback is invoked 6 seconds before the timeout.| 41 42**Return value** 43 44| Type | Description | 45| ------------------------------------- | --------- | 46| [DelaySuspendInfo](#delaysuspendinfo) | Information about the transient task.| 47 48**Error codes** 49 50For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md). 51 52| ID | Error Message| 53| --------- | ------- | 54| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | 55| 9800001 | Memory operation failed. | 56| 9800002 | Failed to write data into parcel. Possible reasons: 1. Invalid parameters; 2. Failed to apply for memory. | 57| 9800003 | Internal transaction failed. | 58| 9800004 | System service operation failed. | 59| 9900001 | Caller information verification failed for a transient task. | 60| 9900002 | Transient task verification failed. | 61 62**Example** 63 64```ts 65import { BusinessError } from '@kit.BasicServicesKit'; 66 67let myReason = 'test requestSuspendDelay'; 68try { 69 let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { 70 // Callback function, which is triggered when the transient task is about to time out. The application can carry out data clear and annotation, and cancel the task in the callback. 71 // The callback is independent of the service of the application. After the request for the transient task is successful, the application normally executes its own service logic. 72 console.info("Request suspension delay will time out."); 73 }) 74 let id = delayInfo.requestId; 75 let time = delayInfo.actualDelayTime; 76 console.info("The requestId is: " + id); 77 console.info("The actualDelayTime is: " + time); 78} catch (error) { 79 console.error(`requestSuspendDelay failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 80} 81``` 82 83 84## backgroundTaskManager.getRemainingDelayTime 85 86getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void 87 88Obtains the remaining time of a transient task. This API uses an asynchronous callback to return the result. 89 90**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 91 92**Parameters** 93 94| Name | Type | Mandatory | Description | 95| --------- | --------------------------- | ---- | ---------------------------------------- | 96| requestId | number | Yes | Request ID of the transient task. | 97| callback | AsyncCallback<number> | Yes | Callback used to return the remaining time of the transient task, in milliseconds.| 98 99**Error codes** 100 101For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md). 102 103| ID | Error Message| 104| --------- | ------- | 105| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | 106| 9800001 | Memory operation failed. | 107| 9800002 | Failed to write data into parcel. Possible reasons: 1. Invalid parameters; 2. Failed to apply for memory. | 108| 9800003 | Internal transaction failed. | 109| 9800004 | System service operation failed. | 110| 9900001 | Caller information verification failed for a transient task. | 111| 9900002 | Transient task verification failed. | 112 113 114**Example** 115 116```ts 117import { BusinessError } from '@kit.BasicServicesKit'; 118 119let id = 1; 120backgroundTaskManager.getRemainingDelayTime(id, (error: BusinessError, res: number) => { 121 if(error) { 122 console.error(`callback => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`); 123 } else { 124 console.log('callback => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); 125 } 126}) 127``` 128 129 130## backgroundTaskManager.getRemainingDelayTime 131 132getRemainingDelayTime(requestId: number): Promise<number> 133 134Obtains the remaining time of a transient task. This API uses a promise to return the result. 135 136**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 137 138**Parameters** 139 140| Name | Type | Mandatory | Description | 141| --------- | ------ | ---- | ---------- | 142| requestId | number | Yes | Request ID of the transient task.| 143 144**Return value** 145 146| Type | Description | 147| --------------------- | ---------------------------------------- | 148| Promise<number> | Promise that returns the remaining time of the transient task, in milliseconds.| 149 150**Error codes** 151 152For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md). 153 154| ID | Error Message| 155| --------- | ------- | 156| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | 157| 9800001 | Memory operation failed. | 158| 9800002 | Failed to write data into parcel. Possible reasons: 1. Invalid parameters; 2. Failed to apply for memory. | 159| 9800003 | Internal transaction failed. | 160| 9800004 | System service operation failed. | 161| 9900001 | Caller information verification failed for a transient task. | 162| 9900002 | Transient task verification failed. | 163 164**Example** 165 166```ts 167import { BusinessError } from '@kit.BasicServicesKit'; 168 169let id = 1; 170backgroundTaskManager.getRemainingDelayTime(id).then((res: number) => { 171 console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); 172}).catch((error: BusinessError) => { 173 console.error(`promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`); 174}) 175``` 176 177 178## backgroundTaskManager.cancelSuspendDelay 179 180cancelSuspendDelay(requestId: number): void 181 182Cancels a transient task. 183 184**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 185 186**Parameters** 187 188| Name | Type | Mandatory | Description | 189| --------- | ------ | ---- | ---------- | 190| requestId | number | Yes | Request ID of the transient task.| 191 192**Error codes** 193 194For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md). 195 196| ID | Error Message| 197| --------- | ------- | 198| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | 199| 9800001 | Memory operation failed. | 200| 9800002 | Failed to write data into parcel. Possible reasons: 1. Invalid parameters; 2. Failed to apply for memory. | 201| 9800003 | Internal transaction failed. | 202| 9800004 | System service operation failed. | 203| 9900001 | Caller information verification failed for a transient task. | 204| 9900002 | Transient task verification failed. | 205 206**Example** 207 208 ```js 209 import { BusinessError } from '@kit.BasicServicesKit'; 210 211 let id = 1; 212 try { 213 backgroundTaskManager.cancelSuspendDelay(id); 214 } catch (error) { 215 console.error(`cancelSuspendDelay failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 216 } 217 ``` 218 219## backgroundTaskManager.getTransientTaskInfo<sup>20+</sup> 220 221getTransientTaskInfo(): Promise<TransientTaskInfo> 222 223Obtains all transient task information, including the remaining quota of the current day. This API uses a promise to return the result. 224 225**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 226 227**Return value** 228 229| Type | Description | 230|-----------------------------------------|-------------| 231| Promise<[TransientTaskInfo](#transienttaskinfo20)> | Promise that returns all transient task information.| 232 233**Error codes** 234 235For details about the error codes, see [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md). 236 237| ID | Error Message| 238| --------- | ------- | 239| 9900001 | Caller information verification failed for a transient task. | 240| 9900003 | Failed to write data into parcel. Possible reasons: 1. Invalid parameters; 2. Failed to apply for memory. | 241| 9900004 | System service operation failed. | 242 243**Example** 244 245```ts 246import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 247import { BusinessError } from '@kit.BasicServicesKit'; 248 249try { 250 backgroundTaskManager.getTransientTaskInfo().then((res: backgroundTaskManager.TransientTaskInfo) => { 251 console.info(`Operation getTransientTaskInfo succeeded. data: ` + JSON.stringify(res)); 252 }).catch((error : BusinessError) => { 253 console.error(`Operation getTransientTaskInfo failed. code is ${error.code} message is ${error.message}`); 254 }); 255} catch (error) { 256 console.error(`Operation getTransientTaskInfo failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 257} 258``` 259 260## backgroundTaskManager.startBackgroundRunning 261 262startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void 263 264Requests a continuous task of a specific type. This API uses an asynchronous callback to return the result. After a continuous task is successfully requested, there will be a notification message without prompt tone. 265 266**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING 267 268**Atomic service API**: This API can be used in atomic services since API version 12. 269 270**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 271 272**Parameters** 273 274| Name | Type | Mandatory | Description | 275| --------- | ---------------------------------- | ---- | ---------------------------------------- | 276| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md).| 277| bgMode | [BackgroundMode](#backgroundmode) | Yes | Type of the continuous task. | 278| wantAgent | [WantAgent](../apis-ability-kit/js-apis-app-ability-wantAgent.md) | Yes | Notification parameters, which are used to specify the target page that is redirected to when a continuous task notification is clicked. | 279| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the continuous task is requested, **err** is **undefined**. Otherwise, **err** is an error object. | 280 281**Error codes** 282 283For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md). 284 285| ID | Error Message | 286| ---- | --------------------- | 287| 201 | Permission denied. | 288| 202 | Not System App. | 289| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | 290| 9800001 | Memory operation failed. | 291| 9800002 | Failed to write data into parcel. Possible reasons: 1. Invalid parameters; 2. Failed to apply for memory. | 292| 9800003 | Internal transaction failed. | 293| 9800004 | System service operation failed. | 294| 9800005 | Continuous task verification failed. | 295| 9800006 | Notification verification failed for a continuous task. | 296| 9800007 | Continuous task storage failed. | 297 298**Example** 299 300```js 301import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 302import { BusinessError } from '@kit.BasicServicesKit'; 303import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 304import { wantAgent, WantAgent } from '@kit.AbilityKit'; 305// In atomic services, please remove the WantAgent import. 306 307function callback(error: BusinessError, data: void) { 308 if (error) { 309 console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); 310 } else { 311 console.info("Operation startBackgroundRunning succeeded"); 312 } 313} 314 315export default class EntryAbility extends UIAbility { 316 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 317 let wantAgentInfo: wantAgent.WantAgentInfo = { 318 // List of operations to be executed after the notification is clicked. 319 wants: [ 320 { 321 bundleName: "com.example.myapplication", 322 abilityName: "EntryAbility" 323 } 324 ], 325 // Type of the operation to perform after the notification is clicked. 326 actionType: wantAgent.OperationType.START_ABILITY, 327 // Custom request code. 328 requestCode: 0, 329 // Execution attribute of the operation to perform after the notification is clicked. 330 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 331 }; 332 333 try { 334 // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. 335 // In atomic services, please replace the following line of code with wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: object) => {. 336 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { 337 try { 338 backgroundTaskManager.startBackgroundRunning(this.context, 339 backgroundTaskManager.BackgroundMode.AUDIO_PLAYBACK, wantAgentObj, callback) 340 } catch (error) { 341 console.error(`Operation startBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 342 } 343 }); 344 } catch (error) { 345 console.error(`Operation getWantAgent failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 346 } 347 } 348}; 349``` 350 351## backgroundTaskManager.startBackgroundRunning 352 353startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void> 354 355Requests a continuous task of a specific type. This API uses a promise to return the result. After a continuous task is successfully requested, there will be a notification message without prompt tone. 356 357**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING 358 359**Atomic service API**: This API can be used in atomic services since API version 12. 360 361**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 362 363**Parameters** 364 365| Name | Type | Mandatory | Description | 366| --------- | ---------------------------------- | ---- | ---------------------------------------- | 367| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md).| 368| bgMode | [BackgroundMode](#backgroundmode) | Yes | Type of the continuous task. | 369| wantAgent | [WantAgent](../apis-ability-kit/js-apis-app-ability-wantAgent.md) | Yes | Notification parameters, which are used to specify the target page that is redirected to when a continuous task notification is clicked. | 370 371**Return value** 372 373| Type | Description | 374| -------------- | ---------------- | 375| Promise\<void> | Promise that returns no value.| 376 377**Error codes** 378 379For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md). 380 381| ID | Error Message | 382| ---- | --------------------- | 383| 201 | Permission denied. | 384| 202 | Not System App. | 385| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | 386| 9800001 | Memory operation failed. | 387| 9800002 | Failed to write data into parcel. Possible reasons: 1. Invalid parameters; 2. Failed to apply for memory. | 388| 9800003 | Internal transaction failed. | 389| 9800004 | System service operation failed. | 390| 9800005 | Continuous task verification failed. | 391| 9800006 | Notification verification failed for a continuous task. | 392| 9800007 | Continuous task storage failed. | 393 394**Example** 395 396```js 397import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 398import { BusinessError } from '@kit.BasicServicesKit'; 399import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 400import { wantAgent, WantAgent } from '@kit.AbilityKit'; 401// In atomic services, please remove the WantAgent import. 402 403export default class EntryAbility extends UIAbility { 404 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 405 let wantAgentInfo: wantAgent.WantAgentInfo = { 406 // List of operations to be executed after the notification is clicked. 407 wants: [ 408 { 409 bundleName: "com.example.myapplication", 410 abilityName: "EntryAbility" 411 } 412 ], 413 // Type of the operation to perform after the notification is clicked. 414 actionType: wantAgent.OperationType.START_ABILITY, 415 // Custom request code. 416 requestCode: 0, 417 // Execution attribute of the operation to perform after the notification is clicked. 418 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 419 }; 420 421 try { 422 // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. 423 // In atomic services, please replace the following line of code with wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: object) => {. 424 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { 425 try { 426 backgroundTaskManager.startBackgroundRunning(this.context, 427 backgroundTaskManager.BackgroundMode.AUDIO_PLAYBACK, wantAgentObj).then(() => { 428 console.info("Operation startBackgroundRunning succeeded"); 429 }).catch((error: BusinessError) => { 430 console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); 431 }); 432 } catch (error) { 433 console.error(`Operation startBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 434 } 435 }); 436 } catch (error) { 437 console.error(`Operation getWantAgent failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 438 } 439 } 440}; 441``` 442 443## backgroundTaskManager.stopBackgroundRunning 444 445stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void 446 447Cancels a continuous task. This API uses an asynchronous callback to return the result. 448 449**Atomic service API**: This API can be used in atomic services since API version 12. 450 451**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 452 453**Parameters** 454 455| Name | Type | Mandatory | Description | 456| -------- | ------------------------- | ---- | ---------------------------------------- | 457| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md).| 458| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the continuous task is canceled, **err** is **undefined**. Otherwise, **err** is an error object.| 459 460**Error codes** 461 462For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md). 463 464| ID | Error Message | 465| ---- | --------------------- | 466| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 467| 9800001 | Memory operation failed. | 468| 9800002 | Failed to write data into parcel. Possible reasons: 1. Invalid parameters; 2. Failed to apply for memory. | 469| 9800003 | Internal transaction failed. | 470| 9800004 | System service operation failed. | 471| 9800005 | Continuous task verification failed. | 472| 9800006 | Notification verification failed for a continuous task. | 473| 9800007 | Continuous task storage failed. | 474 475**Example** 476 477```js 478import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 479import { BusinessError } from '@kit.BasicServicesKit'; 480import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 481 482function callback(error: BusinessError, data: void) { 483 if (error) { 484 console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); 485 } else { 486 console.info("Operation stopBackgroundRunning succeeded"); 487 } 488} 489 490export default class EntryAbility extends UIAbility { 491 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 492 try { 493 backgroundTaskManager.stopBackgroundRunning(this.context, callback); 494 } catch (error) { 495 console.error(`Operation stopBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 496 } 497 } 498}; 499``` 500 501## backgroundTaskManager.stopBackgroundRunning 502 503stopBackgroundRunning(context: Context): Promise<void> 504 505Cancels a continuous task. This API uses a promise to return the result. 506 507**Atomic service API**: This API can be used in atomic services since API version 12. 508 509**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 510 511**Parameters** 512 513| Name | Type | Mandatory | Description | 514| ------- | ------- | ---- | ---------------------------------------- | 515| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md).| 516 517**Return value** 518 519| Type | Description | 520| -------------- | ---------------- | 521| Promise\<void> | Promise that returns no value.| 522 523**Error codes** 524 525For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md). 526 527| ID | Error Message | 528| ---- | --------------------- | 529| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 530| 9800001 | Memory operation failed. | 531| 9800002 | Failed to write data into parcel. Possible reasons: 1. Invalid parameters; 2. Failed to apply for memory. | 532| 9800003 | Internal transaction failed. | 533| 9800004 | System service operation failed. | 534| 9800005 | Continuous task verification failed. | 535| 9800006 | Notification verification failed for a continuous task. | 536| 9800007 | Continuous task storage failed. | 537 538**Example** 539 540```js 541import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 542import { BusinessError } from '@kit.BasicServicesKit'; 543import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 544 545export default class EntryAbility extends UIAbility { 546 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 547 try { 548 backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { 549 console.info("Operation stopBackgroundRunning succeeded"); 550 }).catch((error: BusinessError) => { 551 console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); 552 }); 553 } catch (error) { 554 console.error(`Operation stopBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 555 } 556 } 557}; 558``` 559 560## backgroundTaskManager.startBackgroundRunning<sup>12+</sup> 561 562startBackgroundRunning(context: Context, bgModes: string[], wantAgent: WantAgent): Promise<ContinuousTaskNotification> 563 564Requests continuous tasks of multiple types. This API uses a promise to return the result. After a continuous task is successfully requested, there will be a notification message without prompt tone. 565 566**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING 567 568**Atomic service API**: This API can be used in atomic services since API version 12. 569 570**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 571 572**Parameters** 573 574| Name | Type | Mandatory | Description | 575| --------- | ---------------------------------- | ---- | ---------------------------------------- | 576| context | [Context](../apis-ability-kit/js-apis-inner-application-context.md) | Yes | Application context.| 577| bgModes | string[] | Yes | Types of continuous tasks. For details about the available options, see [Item](../../task-management/continuous-task.md#use-cases).<br> **Note**: One or more types can be passed.| 578| wantAgent | [WantAgent](../apis-ability-kit/js-apis-app-ability-wantAgent.md) | Yes | Notification parameters, which are used to specify the target page that is redirected to when a continuous task notification is clicked. | 579 580**Return value** 581 582| Type | Description | 583| -------------- | ---------------- | 584| Promise\<ContinuousTaskNotification> | Promise that returns an object of the [ContinuousTaskNotification](#continuoustasknotification12) type.| 585 586**Error codes** 587 588For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md). 589 590| ID | Error Message | 591| ---- | --------------------- | 592| 201 | Permission denied. | 593| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | 594| 9800001 | Memory operation failed. | 595| 9800002 | Failed to write data into parcel. Possible reasons: 1. Invalid parameters; 2. Failed to apply for memory. | 596| 9800003 | Internal transaction failed. | 597| 9800004 | System service operation failed. | 598| 9800005 | Continuous task verification failed. | 599| 9800006 | Notification verification failed for a continuous task. | 600| 9800007 | Continuous task storage failed. | 601 602**Example** 603 604```js 605import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 606import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 607import { window } from '@kit.ArkUI'; 608import { BusinessError } from '@kit.BasicServicesKit'; 609import { notificationManager } from '@kit.NotificationKit'; 610import { wantAgent, WantAgent } from '@kit.AbilityKit'; 611// In atomic services, please remove the WantAgent import. 612 613export default class EntryAbility extends UIAbility { 614 id: number = 0; // Save the notification ID. 615 616 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 617 let wantAgentInfo: wantAgent.WantAgentInfo = { 618 // List of operations to be executed after the notification is clicked. 619 wants: [ 620 { 621 bundleName: "com.example.myapplication", 622 abilityName: "EntryAbility" 623 } 624 ], 625 // Type of the operation to perform after the notification is clicked. 626 actionType: wantAgent.OperationType.START_ABILITY, 627 // Custom request code. 628 requestCode: 0, 629 // Execution attribute of the operation to perform after the notification is clicked. 630 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 631 }; 632 633 try { 634 // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. 635 // In atomic services, please replace the following line of code with wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: object) => {. 636 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { 637 try { 638 let list: Array<string> = ["dataTransfer"]; 639 // In atomic services, let list: Array<string> = ["audioPlayback"]; 640 backgroundTaskManager.startBackgroundRunning(this.context, list, wantAgentObj).then((res: backgroundTaskManager.ContinuousTaskNotification) => { 641 console.info("Operation startBackgroundRunning succeeded"); 642 // For a continuous task of the upload and download type, the application can use the notification ID returned in res to update the notification, for example, sending a template notification with a progress bar. 643 this.id = res.notificationId; 644 }).catch((error: BusinessError) => { 645 console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); 646 }); 647 } catch (error) { 648 console.error(`Operation startBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 649 } 650 }); 651 } catch (error) { 652 console.error(`Operation getWantAgent failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 653 } 654 } 655 656 // The application updates its progress. 657 updateProcess(process: number) { 658 // The application defines the download notification template. 659 let downLoadTemplate: notificationManager.NotificationTemplate = { 660 name: 'downloadTemplate', // Currently, only downloadTemplate is supported. Retain the value. 661 data: { 662 title: 'File download: music.mp4', // Mandatory. 663 fileName: 'senTemplate', // Mandatory. 664 progressValue: process, // The application updates the progress, which is user-defined. 665 } 666 }; 667 let request: notificationManager.NotificationRequest = { 668 content: { 669 // System live view type, which remains unchanged. 670 notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW, 671 systemLiveView: { 672 typeCode: 8, // Set this parameter to 8 for the upload and download type. Currently, only the upload and download type is supported. Retain the value. 673 title: "test", // Customized by the application. 674 text: "test", // Customized by the application. 675 } 676 }, 677 id: this.id, // The value must be the ID returned for a continuous-task request. Otherwise, the application fails to update the notification. 678 notificationSlotType: notificationManager.SlotType.LIVE_VIEW, // Live view type. Retain the value. 679 template: downLoadTemplate // Name of the template to be set for the application. 680 }; 681 682 try { 683 notificationManager.publish(request).then(() => { 684 console.info("publish success, id= " + this.id); 685 }).catch((err: BusinessError) => { 686 console.error(`publish fail: ${JSON.stringify(err)}`); 687 }); 688 } catch (err) { 689 console.error(`publish fail: ${JSON.stringify(err)}`); 690 } 691 } 692}; 693``` 694 695## backgroundTaskManager.updateBackgroundRunning<sup>12+</sup> 696 697updateBackgroundRunning(context: Context, bgModes: string[]): Promise<ContinuousTaskNotification> 698 699Updates continuous tasks of multiple types. This API uses a promise to return the result. After a continuous task is successfully updated, there will be a notification message without prompt tone. 700 701**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING 702 703**Atomic service API**: This API can be used in atomic services since API version 12. 704 705**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 706 707**Parameters** 708 709| Name | Type | Mandatory | Description | 710| --------- | ---------------------------------- | ---- | ---------------------------------------- | 711| context | [Context](../apis-ability-kit/js-apis-inner-application-context.md) | Yes | Application context.| 712| bgModes | string[] | Yes | Types of continuous tasks after the update. For details about the available options, see [Item](../../task-management/continuous-task.md#use-cases).<br> **Note**: One or more types can be passed.| 713 714**Return value** 715 716| Type | Description | 717| -------------- | ---------------- | 718| Promise\<ContinuousTaskNotification> | Promise that returns an object of the [ContinuousTaskNotification](#continuoustasknotification12) type.| 719 720**Error codes** 721 722For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md). 723 724| ID | Error Message | 725| ---- | --------------------- | 726| 201 | Permission denied. | 727| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | 728| 9800001 | Memory operation failed. | 729| 9800002 | Failed to write data into parcel. Possible reasons: 1. Invalid parameters; 2. Failed to apply for memory. | 730| 9800003 | Internal transaction failed. | 731| 9800004 | System service operation failed. | 732| 9800005 | Continuous task verification failed. | 733| 9800006 | Notification verification failed for a continuous task. | 734| 9800007 | Continuous task storage failed. | 735 736**Example** 737 738```js 739import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 740import { BusinessError } from '@kit.BasicServicesKit'; 741import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 742 743export default class EntryAbility extends UIAbility { 744 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 745 try { 746 // You must call startBackgroundRunning before updateBackgroundRunning. Here it is assumed that you have called startBackgroundRunning. 747 let list: Array<string> = ["audioPlayback"]; 748 backgroundTaskManager.updateBackgroundRunning(this.context, list).then(() => { 749 console.info("Operation updateBackgroundRunning succeeded"); 750 }).catch((error: BusinessError) => { 751 console.error(`Operation updateBackgroundRunning failed. code is ${error.code} message is ${error.message}`); 752 }); 753 } catch (error) { 754 console.error(`Operation updateBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 755 } 756 } 757}; 758``` 759 760## backgroundTaskManager.getAllContinuousTasks<sup>20+</sup> 761 762getAllContinuousTasks(context: Context): Promise<ContinuousTaskInfo[]> 763 764Obtains all continuous task information, including the task ID and type. This API uses a promise to return the result. 765 766**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING 767 768**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 769 770**Parameters** 771 772| Name | Type | Mandatory | Description | 773| --------- | ---------------------------------- | ---- | ---------------------------------------- | 774| context | [Context](../apis-ability-kit/js-apis-inner-application-context.md) | Yes | Application context.| 775 776**Return value** 777 778| Type | Description | 779|-----------------------------------------------|-------------| 780| Promise<[ContinuousTaskInfo](#continuoustaskinfo20)[]> | Promise that returns all continuous task information.| 781 782**Error codes** 783 784For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md). 785 786| ID | Error Message| 787| --------- | ------- | 788| 201 | Permission denied. | 789| 9800002 | Failed to write data into parcel. Possible reasons: 1. Invalid parameters; 2. Failed to apply for memory. | 790| 9800004 | System service operation failed. | 791| 9800005 | Continuous task verification failed. | 792 793**Example** 794 795```ts 796import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 797import { BusinessError } from '@kit.BasicServicesKit'; 798import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 799 800export default class EntryAbility extends UIAbility { 801 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 802 try { 803 // If no continuous task is requested, an empty array is obtained. 804 backgroundTaskManager.getAllContinuousTasks(this.context).then((res: backgroundTaskManager.ContinuousTaskInfo[]) => { 805 console.info(`Operation getAllContinuousTasks succeeded. data: ` + JSON.stringify(res)); 806 }).catch((error: BusinessError) => { 807 console.error(`Operation getAllContinuousTasks failed. code is ${error.code} message is ${error.message}`); 808 }); 809 } catch (error) { 810 console.error(`Operation getAllContinuousTasks failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 811 } 812 } 813}; 814``` 815 816## backgroundTaskManager.on('continuousTaskCancel')<sup>15+</sup> 817 818on(type: 'continuousTaskCancel', callback: Callback<ContinuousTaskCancelInfo>): void 819 820Subscribes to continuous task cancellation events. This API uses an asynchronous callback to return the result. 821 822**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING 823 824**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 825 826**Parameters** 827 828| Name | Type | Mandatory | Description | 829| --------- | ---------------------------------- | ---- | ---------------------------------------- | 830| type | string | Yes | Cancels a continuous task. The value is fixed at **'continuousTaskCancel'**.| 831| callback | Callback\<[ContinuousTaskCancelInfo](#continuoustaskcancelinfo15)> | Yes | Callback used to return information such as the reason for canceling a continuous task.| 832 833**Error codes** 834 835For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 836 837| ID | Error Message | 838| ---- | --------------------- | 839| 201 | Permission denied. | 840| 401 | Parameter error. Possible cause: 1. Callback parameter error; 2. Register a exist callback type; 3. Parameter verification failed. | 841 842**Example** 843 844```js 845import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 846import { BusinessError } from '@kit.BasicServicesKit'; 847import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 848 849function callback(info: backgroundTaskManager.ContinuousTaskCancelInfo) { 850 console.info('continuousTaskCancel callback id ' + info.id); 851 console.info('continuousTaskCancel callback reason ' + info.reason); 852} 853 854export default class EntryAbility extends UIAbility { 855 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 856 try { 857 backgroundTaskManager.on("continuousTaskCancel", callback); 858 } catch (error) { 859 console.error(`Operation onContinuousTaskCancel failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 860 } 861 } 862}; 863``` 864## backgroundTaskManager.off('continuousTaskCancel')<sup>15+</sup> 865 866off(type: 'continuousTaskCancel', callback?: Callback<ContinuousTaskCancelInfo>): void 867 868Unsubscribes from continuous task cancellation events. This API uses an asynchronous callback to return the result. 869 870**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING 871 872**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 873 874**Parameters** 875 876| Name | Type | Mandatory | Description | 877| --------- | ---------------------------------- | ---- | ---------------------------------------- | 878| type | string | Yes | Cancels a continuous task. The value is fixed at **'continuousTaskCancel'**.| 879| callback | Callback\<[ContinuousTaskCancelInfo](#continuoustaskcancelinfo15)> | No | Callback for which listening is cancelled. If this parameter is left unspecified, all registered callbacks are cancelled.| 880 881**Error codes** 882 883For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 884 885| ID | Error Message | 886| ---- | --------------------- | 887| 201 | Permission denied. | 888| 401 | Parameter error. Possible cause: 1. Callback parameter error; 2. Unregister type has not register; 3. Parameter verification failed. | 889 890**Example** 891 892```js 893import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 894import { BusinessError } from '@kit.BasicServicesKit'; 895import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 896 897function callback(info: backgroundTaskManager.ContinuousTaskCancelInfo) { 898 console.info('continuousTaskCancel callback id ' + info.id); 899 console.info('continuousTaskCancel callback reason ' + info.reason); 900} 901 902export default class EntryAbility extends UIAbility { 903 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 904 try { 905 backgroundTaskManager.off("continuousTaskCancel", callback); 906 } catch (error) { 907 console.error(`Operation onContinuousTaskCancel failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 908 } 909 } 910}; 911``` 912## backgroundTaskManager.on('continuousTaskSuspend')<sup>20+</sup> 913 914on(type: 'continuousTaskSuspend', callback: Callback<ContinuousTaskSuspendInfo>): void 915 916Registers a listener for continuous task suspension. This API uses an asynchronous callback to return the result. 917 918**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING 919 920**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 921 922**Parameters** 923 924| Name | Type | Mandatory | Description | 925| --------- | ---------------------------------- | ---- | ---------------------------------------- | 926| type | string | Yes | Event type. The value is fixed at **'continuousTaskSuspend'**, indicating that the continuous task is suspended.| 927| callback | Callback\<[ContinuousTaskSuspendInfo](#continuoustasksuspendinfo20)> | Yes | Callback used to return information such as the reason for suspending the continuous task.| 928 929**Error codes** 930 931For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md). 932 933| ID | Error Message | 934| ---- | --------------------- | 935| 201 | Permission denied. | 936| 9800005 | Continuous task verification failed. | 937 938**Example** 939 940 941```js 942import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 943import { BusinessError } from '@kit.BasicServicesKit'; 944import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 945 946function callback(info: backgroundTaskManager.ContinuousTaskSuspendInfo) { 947 console.info('continuousTaskSuspend callback continuousTaskId: ' + info.continuousTaskId); 948 console.info('continuousTaskSuspend callback suspendState: ' + info.suspendState); 949 console.info('continuousTaskSuspend callback suspendReason: ' + info.suspendReason); 950} 951 952export default class EntryAbility extends UIAbility { 953 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 954 try { 955 backgroundTaskManager.on("continuousTaskSuspend", callback); 956 } catch (error) { 957 console.error(`Operation onContinuousTaskSuspend failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 958 } 959 } 960}; 961``` 962## backgroundTaskManager.off('continuousTaskSuspend')<sup>20+</sup> 963 964off(type: 'continuousTaskSuspend', callback?: Callback<ContinuousTaskSuspendInfo>): void 965 966Unregisters from the listener for continuous task suspension. This API uses an asynchronous callback to return the result. 967 968**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING 969 970**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 971 972**Parameters** 973 974| Name | Type | Mandatory | Description | 975| --------- | ---------------------------------- | ---- | ---------------------------------------- | 976| type | string | Yes | Event type. The value is fixed at **'continuousTaskSuspend'**, indicating that the continuous task is suspended.| 977| callback | Callback\<[ContinuousTaskSuspendInfo](#continuoustasksuspendinfo20)> | No | Callback used to unregister from the listener for continuous task suspension. If this parameter is not passed, all listeners are unsubscribed from.| 978 979**Error codes** 980 981For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md). 982 983| ID | Error Message | 984| ---- | --------------------- | 985| 201 | Permission denied. | 986| 9800005 | Continuous task verification failed. | 987 988**Example** 989 990```js 991import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 992import { BusinessError } from '@kit.BasicServicesKit'; 993import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 994 995function callback(info: backgroundTaskManager.ContinuousTaskSuspendInfo) { 996 console.info('continuousTaskSuspend callback continuousTaskId: ' + info.continuousTaskId); 997 console.info('continuousTaskSuspend callback suspendState: ' + info.suspendState); 998 console.info('continuousTaskSuspend callback suspendReason: ' + info.suspendReason); 999} 1000 1001export default class EntryAbility extends UIAbility { 1002 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 1003 try { 1004 backgroundTaskManager.off("continuousTaskSuspend", callback); 1005 } catch (error) { 1006 console.error(`Operation offContinuousTaskSuspend failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 1007 } 1008 } 1009}; 1010``` 1011## backgroundTaskManager.on('continuousTaskActive')<sup>20+</sup> 1012 1013on(type: 'continuousTaskActive', callback: Callback<ContinuousTaskActiveInfo>): void 1014 1015Registers a listener for continuous task activation. This API uses an asynchronous callback to return the result. The application returns to the foreground to activate the suspended continuous task. 1016 1017**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING 1018 1019**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 1020 1021**Parameters** 1022 1023| Name | Type | Mandatory | Description | 1024| --------- | ---------------------------------- | ---- | ---------------------------------------- | 1025| type | string | Yes | Event type. The value is fixed at **'continuousTaskActive'**, indicating that the continuous task is activated.| 1026| callback | Callback\<[ContinuousTaskActiveInfo](#continuoustaskactiveinfo20)> | Yes | Callback used to return the activation information about a continuous task.| 1027 1028**Error codes** 1029 1030For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md). 1031 1032| ID | Error Message | 1033| ---- | --------------------- | 1034| 201 | Permission denied. | 1035| 9800005 | Continuous task verification failed. | 1036 1037**Example** 1038 1039```js 1040import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 1041import { BusinessError } from '@kit.BasicServicesKit'; 1042import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 1043 1044function callback(info: backgroundTaskManager.ContinuousTaskActiveInfo) { 1045 console.info('continuousTaskActive callback id: ' + info.id); 1046} 1047 1048export default class EntryAbility extends UIAbility { 1049 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 1050 try { 1051 backgroundTaskManager.on("continuousTaskActive", callback); 1052 } catch (error) { 1053 console.error(`Operation onContinuousTaskActive failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 1054 } 1055 } 1056}; 1057``` 1058## backgroundTaskManager.off('continuousTaskActive')<sup>20+</sup> 1059 1060off(type: 'continuousTaskActive', callback?: Callback<ContinuousTaskActiveInfo>): void 1061 1062Unregisters from the listener for continuous task activation. This API uses an asynchronous callback to return the result. 1063 1064**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING 1065 1066**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 1067 1068**Parameters** 1069 1070| Name | Type | Mandatory | Description | 1071| --------- | ---------------------------------- | ---- | ---------------------------------------- | 1072| type | string | Yes | Event type. The value is fixed at **'continuousTaskActive'**, indicating that the continuous task is activated.| 1073| callback | Callback\<[ContinuousTaskActiveInfo](#continuoustaskactiveinfo20)> | No | Callback used to unregister from the listener for continuous task activation. If this parameter is not passed, all listeners are unsubscribed from.| 1074 1075**Error codes** 1076 1077For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md). 1078 1079| ID | Error Message | 1080| ---- | --------------------- | 1081| 201 | Permission denied. | 1082| 9800005 | Continuous task verification failed. | 1083 1084**Example** 1085 1086```js 1087import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 1088import { BusinessError } from '@kit.BasicServicesKit'; 1089import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 1090 1091function callback(info: backgroundTaskManager.ContinuousTaskActiveInfo) { 1092 console.info('continuousTaskActive callback id: ' + info.id); 1093} 1094 1095export default class EntryAbility extends UIAbility { 1096 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 1097 try { 1098 backgroundTaskManager.off("continuousTaskActive", callback); 1099 } catch (error) { 1100 console.error(`Operation offContinuousTaskActive failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 1101 } 1102 } 1103}; 1104``` 1105 1106## DelaySuspendInfo 1107 1108Defines the information about the transient task. 1109 1110**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 1111 1112| Name | Type | Read-Only | Optional | Description | 1113| --------------- | ------ | ---- | ---- | ---------------------------------------- | 1114| requestId | number | No | No | Request ID of the transient task. | 1115| actualDelayTime | number | No | No | Actual duration of the transient task requested by the application, in milliseconds.<br> **Note**: The maximum duration is 3 minutes in normal cases. In the case of a [low battery](../apis-basic-services-kit/js-apis-battery-info.md), the maximum duration is decreased to 1 minute.| 1116 1117## TransientTaskInfo<sup>20+</sup> 1118 1119Describes all transient task information. 1120 1121**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 1122 1123| Name | Type | Read-Only | Optional | Description | 1124| --------------- |-----------------------------------------| ---- | ---- |-----------------| 1125| remainingQuota | number | No | No | Remaining quota of the application on the current day, in ms. | 1126| transientTasks | [DelaySuspendInfo](#delaysuspendinfo)[] | No | No | All information about the requested transient task.| 1127 1128## BackgroundMode 1129 1130Type of the continuous task. 1131 1132**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 1133 1134| Name | Value | Description | 1135| ----------------------- | ---- | --------------------- | 1136| DATA_TRANSFER | 1 | Data transfer. | 1137| AUDIO_PLAYBACK | 2 | Audio and video playback.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 1138| AUDIO_RECORDING | 3 | Audio recording. | 1139| LOCATION | 4 | Positioning and navigation. | 1140| BLUETOOTH_INTERACTION | 5 | Bluetooth-related services. | 1141| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 1142| VOIP<sup>13+</sup> | 8 | Audio and video calls. | 1143| TASK_KEEPING | 9 | Computing task (for 2-in-1 devices only). | 1144 1145## ContinuousTaskNotification<sup>12+</sup> 1146 1147Describes the information about a continuous-task notification. 1148 1149**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 1150 1151| Name | Type | Read-Only | Optional | Description | 1152| --------------- | ------ | ---- | ---- | ---------------------------------------- | 1153| slotType | [notificationManager.SlotType](../apis-notification-kit/js-apis-notificationManager.md#slottype) | No | No | Slot type of a continuous-task notification.<br>**Note**: After a continuous task is successfully requested or updated, no prompt tone is played.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 1154| contentType | [notificationManager.ContentType](../apis-notification-kit/js-apis-notificationManager.md#contenttype) | No | No | Content type of a continuous-task notification.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 1155| notificationId | number | No | No | ID of the continuous-task notification.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 1156| continuousTaskId<sup>15+</sup> | number | No | Yes | ID of a continuous task| 1157 1158## ContinuousTaskCancelInfo<sup>15+</sup> 1159 1160Describes the information about the cancellation of a continuous task. 1161 1162**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 1163 1164| Name | Type | Read-Only | Optional | Description | 1165| --------------- | ------ | ---- | ---- | ---------------------------------------- | 1166| reason | [ContinuousTaskCancelReason](#continuoustaskcancelreason15) | No | No | Reason for canceling the continuous task.| 1167| id | number | No | No | ID of the continuous task canceled.| 1168 1169## ContinuousTaskCancelReason<sup>15+</sup> 1170 1171Describes the reason for canceling a continuous task. 1172 1173**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 1174 1175| Name | Value | Description | 1176| ----------------------- | ---- | --------------------- | 1177| USER_CANCEL | 1 | The task is canceled by the user. | 1178| SYSTEM_CANCEL | 2 | The task is canceled by the system. | 1179| USER_CANCEL_REMOVE_NOTIFICATION | 3 | User removal notification. This value is reserved. | 1180| SYSTEM_CANCEL_DATA_TRANSFER_LOW_SPEED | 4 | A continuous task of the DATA_TRANSFER type is requested, but the data transmission rate is low. This value is reserved. | 1181| SYSTEM_CANCEL_AUDIO_PLAYBACK_NOT_USE_AVSESSION | 5 | A continuous task of the AUDIO_PLAYBACK type is requested, but the [AVSession](../../media/avsession/avsession-overview.md) is not accessed. This value is reserved. | 1182| SYSTEM_CANCEL_AUDIO_PLAYBACK_NOT_RUNNING | 6 | A continuous task of the AUDIO_PLAYBACK type is requested, but the audio and video are not played. This value is reserved. | 1183| SYSTEM_CANCEL_AUDIO_RECORDING_NOT_RUNNING | 7 | A continuous task of the AUDIO_RECORDING type is requested, but audio recording is not in progress. This value is reserved. | 1184| SYSTEM_CANCEL_NOT_USE_LOCATION | 8 | A continuous task of the LOCATION type is requested, but location and navigation are not used. This value is reserved. | 1185| SYSTEM_CANCEL_NOT_USE_BLUETOOTH | 9 | A continuous task of the BLUETOOTH_INTERACTION type is requested, but Bluetooth-related services are not used. This value is reserved. | 1186| SYSTEM_CANCEL_NOT_USE_MULTI_DEVICE | 10 | A continuous task of the MULTI_DEVICE_CONNECTION type is requested, but multi-device connection is not used. This value is reserved. | 1187| SYSTEM_CANCEL_USE_ILLEGALLY | 11 | A continuous task of an invalid type is used. For example, a continuous task of the AUDIO_PLAYBACK type is requested, but the audio and video playback and location and navigation services are used. This value is reserved. | 1188 1189## BackgroundSubMode<sup>16+</sup> 1190 1191Subtype of a continuous task. 1192 1193**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 1194 1195| Name | Value | Description | 1196| ----------------------- | ---- | --------------------- | 1197| CAR_KEY | 1 | Car key.<br>Note: The car key subtype takes effect only when a continuous task of the BLUETOOTH_INTERACTION type is requested. | 1198 1199## BackgroundModeType<sup>16+</sup> 1200 1201Type of a continuous task. 1202 1203**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 1204 1205| Name | Value | Description | 1206| ----------------------- | ---- | --------------------- | 1207| SUB_MODE | 'subMode' | Subtype. | 1208 1209## ContinuousTaskSuspendInfo<sup>20+</sup> 1210 1211Describes the information about continuous task suspension. 1212 1213**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 1214 1215| Name | Type | Read-Only | Optional | Description | 1216| --------------- | ------ | ---- | ---- | ---------------------------------------- | 1217| continuousTaskId | number | No | No | ID of a suspended continuous task.| 1218| suspendState | boolean | No | No | Continuous task state. The value **false** indicates that the task is activated, and the value **true** indicates that the task is suspended.| 1219| suspendReason | [ContinuousTaskSuspendReason](#continuoustasksuspendreason20) | No | No | Reason why the continuous task is suspended.| 1220 1221## ContinuousTaskSuspendReason<sup>20+</sup> 1222 1223Describes the reason why the continuous task is suspended. 1224 1225**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 1226 1227| Name | Value | Description | 1228| ----------------------- | ---- | --------------------- | 1229| SYSTEM_SUSPEND_DATA_TRANSFER_LOW_SPEED | 4 | A continuous task of the DATA_TRANSFER type is requested, but the data transmission rate is low. | 1230| SYSTEM_SUSPEND_AUDIO_PLAYBACK_NOT_USE_AVSESSION | 5 | A continuous task of the AUDIO_PLAYBACK type is requested, but the [AVSession](../../media/avsession/avsession-overview.md) is not accessed. | 1231| SYSTEM_SUSPEND_AUDIO_PLAYBACK_NOT_RUNNING | 6 | A continuous task of the AUDIO_PLAYBACK type is requested, but the audio and video are not played. | 1232| SYSTEM_SUSPEND_AUDIO_RECORDING_NOT_RUNNING | 7 | A continuous task of the AUDIO_RECORDING type is requested, but audio recording is not in progress. | 1233| SYSTEM_SUSPEND_LOCATION_NOT_USED | 8 | A continuous task of the LOCATION type is requested, but location and navigation are not used.| 1234| SYSTEM_SUSPEND_BLUETOOTH_NOT_USED | 9 | A continuous task of the BLUETOOTH_INTERACTION type is requested, but Bluetooth-related services are not used.| 1235| SYSTEM_SUSPEND_MULTI_DEVICE_NOT_USED | 10 | A continuous task of the MULTI_DEVICE_CONNECTION type is requested, but multi-device connection is not used. | 1236| SYSTEM_SUSPEND_USED_ILLEGALLY | 11 | A continuous task of an invalid type is used. For example, a continuous task of the AUDIO_PLAYBACK type is requested, but the audio and video playback and location and navigation services are used. This value is reserved. | 1237| SYSTEM_SUSPEND_SYSTEM_LOAD_WARNING | 12 | A continuous task is suspended due to high system load. This value is reserved. | 1238 1239## ContinuousTaskActiveInfo<sup>20+</sup> 1240 1241Describes the activation information of a continuous task. 1242 1243**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 1244 1245| Name | Type | Read-Only | Optional | Description | 1246| --------------- | ------ | ---- | ---- | ---------------------------------------- | 1247| id | number | No | No | ID of the activated continuous task.| 1248 1249## ContinuousTaskInfo<sup>20+</sup> 1250 1251Describes the continuous task information. 1252 1253**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 1254 1255| Name | Type | Read-Only | Optional | Description | 1256|-------------|----------| ---- | ---- |-----------------------| 1257| abilityName | string | No | No | UIAbility name. | 1258| uid | number | No | No | Application UID. | 1259| pid | number | No | No | Application PID. | 1260| isFromWebView | boolean | No | No | Whether to request a continuous task in WebView mode, that is, whether to request a continuous task through the system proxy application. | 1261| [backgroundModes](#backgroundmode) | string[] | No | No | Type of the continuous task. | 1262| [backgroundSubModes](#backgroundsubmode16) | string[] | No | No | Subtype of a continuous task. | 1263| notificationId | number | No | No | Notification ID. | 1264| continuousTaskId | number | No | No | ID of a continuous task. | 1265| abilityId | number | No | No | UIAbility ID. | 1266| wantAgentBundleName | string | No | No | Bundle name configured for **WantAgent**, a notification parameter used to specify the target page when a continuous task notification is tapped. | 1267| wantAgentAbilityName | string | No | No | Ability name configured for **WantAgent**, a notification parameter used to specify the target page when a continuous task notification is tapped.| 1268