1# @ohos.backgroundTaskManager (Background Task Management) 2 3The **BackgroundTaskManager** module provides APIs to manage background tasks. 4 5If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task to delay the suspension or a continuous task to prevent the suspension. 6 7If an application has a task that needs to be continued when the application is switched to the background and can be completed within a short period of time, the application can request a transient task. For example, if a user chooses to clear junk files in the **Files** application and exits the application, the application can request a transient task to complete the cleanup. 8 9If an application has a service that can be intuitively perceived by users and needs to run in the background for a long period of time (for example, music playback in the background), the application can request a continuous task. 10 11 12> **NOTE** 13> 14> - This module is deprecated since API version 9. You are advised to use [@ohos.resourceschedule.backgroundTaskManager](js-apis-resourceschedule-backgroundTaskManager.md) instead. 15> 16> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. 17 18 19## Modules to Import 20 21```ts 22import backgroundTaskManager from '@ohos.backgroundTaskManager'; 23``` 24 25 26## backgroundTaskManager.requestSuspendDelay 27 28requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspendInfo 29 30Requests delayed suspension after the application switches to the background. 31 32The default duration of delayed suspension is 3 minutes when the battery level is higher than or equal to the broadcast low battery level and 1 minute when the battery level is lower than the broadcast low battery level. 33 34**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 35 36**Parameters** 37 38| Name | Type | Mandatory | Description | 39| -------- | -------------------- | ---- | ------------------------------ | 40| reason | string | Yes | Reason for delayed transition to the suspended state. | 41| callback | Callback<void> | Yes | Invoked when a delay is about to time out. Generally, this callback is used to notify the application 6 seconds before the delay times out.| 42 43**Return value** 44 45| Type | Description | 46| ------------------------------------- | --------- | 47| [DelaySuspendInfo](#delaysuspendinfo) | Information about the suspension delay.| 48 49**Example** 50 51 ```ts 52 import backgroundTaskManager from '@ohos.backgroundTaskManager'; 53 import { BusinessError } from '@ohos.base'; 54 55 // Set the reason for delayed suspension. 56 let myReason = 'test requestSuspendDelay'; 57 // Request delayed suspension. 58 let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { 59 console.info("Request suspension delay will time out."); 60 }) 61 // Print the delayed suspension information. 62 let id = delayInfo.requestId; 63 let time = delayInfo.actualDelayTime; 64 console.info("The requestId is: " + id); 65 console.info("The actualDelayTime is: " + time); 66 ``` 67 68 69## backgroundTaskManager.getRemainingDelayTime 70 71getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void 72 73Obtains the remaining duration before the application is suspended. This API uses an asynchronous callback to return the result. 74 75**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 76 77**Parameters** 78 79| Name | Type | Mandatory | Description | 80| --------- | --------------------------- | ---- | ---------------------------------------- | 81| requestId | number | Yes | ID of the suspension delay request. The value is obtained by calling [requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay).| 82| callback | AsyncCallback<number> | Yes | Callback used to return the remaining duration before the application is suspended, in milliseconds.| 83 84**Example** 85 86 ```ts 87 import backgroundTaskManager from '@ohos.backgroundTaskManager'; 88 import { BusinessError } from '@ohos.base'; 89 90 let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); 91 backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId, (err: BusinessError, res: number) => { 92 if(err) { 93 console.log('callback => Operation getRemainingDelayTime failed. Cause: ' + err.code); 94 } else { 95 console.log('callback => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); 96 } 97 }) 98 ``` 99 100 101## backgroundTaskManager.getRemainingDelayTime 102 103getRemainingDelayTime(requestId: number): Promise<number> 104 105Obtains the remaining duration before the application is suspended. This API uses a promise to return the result. 106 107**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 108 109**Parameters** 110 111| Name | Type | Mandatory | Description | 112| --------- | ------ | ---- | ---------- | 113| requestId | number | Yes | ID of the suspension delay request. The value is obtained by calling [requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay).| 114 115**Return value** 116 117| Type | Description | 118| --------------------- | ---------------------------------------- | 119| Promise<number> | Promise used to return the remaining duration before the application is suspended, in milliseconds.| 120 121**Example** 122 123```ts 124import backgroundTaskManager from '@ohos.backgroundTaskManager'; 125import { BusinessError } from '@ohos.base'; 126 127let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); 128 backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId).then((res:number) => { 129 console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); 130}).catch((err : BusinessError) => { 131 console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); 132}) 133``` 134 135 136## backgroundTaskManager.cancelSuspendDelay 137 138cancelSuspendDelay(requestId: number): void 139 140Cancels the suspension delay. 141 142**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 143 144**Parameters** 145 146| Name | Type | Mandatory | Description | 147| --------- | ------ | ---- | ---------- | 148| requestId | number | Yes | ID of the suspension delay request. The value is obtained by calling [requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay).| 149 150**Example** 151 152 ```ts 153 let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); 154 backgroundTaskManager.cancelSuspendDelay(delayInfo.requestId); 155 ``` 156 157 158## backgroundTaskManager.startBackgroundRunning<sup>8+</sup> 159 160startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void 161 162Requests a continuous task from the system. This API uses an asynchronous callback to return the result. 163 164**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING 165 166**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 167 168**Parameters** 169 170| Name | Type | Mandatory| Description | 171| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | 172| 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).| 173| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | 174| wantAgent | [WantAgent](../apis-ability-kit/js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | 175| callback | AsyncCallback<void> | Yes | Callback used to return the result. | 176 177**Example** 178 179FA model: 180 181```js 182import backgroundTaskManager from '@ohos.backgroundTaskManager'; 183import featureAbility from '@ohos.ability.featureAbility'; 184import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; 185import { BusinessError } from '@ohos.base'; 186 187function callback(err: BusinessError, data: void) { 188 if (err) { 189 console.error("Operation startBackgroundRunning failed Cause: " + err); 190 } else { 191 console.info("Operation startBackgroundRunning succeeded"); 192 } 193} 194 195let wantAgentInfo : wantAgent.WantAgentInfo = { 196 wants: [ 197 { 198 bundleName: "com.example.myapplication", 199 abilityName: "EntryAbility" 200 } 201 ], 202 operationType: wantAgent.OperationType.START_ABILITY, 203 requestCode: 0, 204 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 205}; 206 207wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => { 208 backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), 209 backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) 210}); 211 212``` 213 214Stage model: 215 216```ts 217import UIAbility from '@ohos.app.ability.UIAbility'; 218import backgroundTaskManager from '@ohos.backgroundTaskManager'; 219import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; 220import Want from '@ohos.app.ability.Want'; 221import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 222import { BusinessError } from '@ohos.base'; 223 224function callback(err: BusinessError, data: void) { 225 if (err) { 226 console.error("Operation startBackgroundRunning failed Cause: " + err); 227 } else { 228 console.info("Operation startBackgroundRunning succeeded"); 229 } 230} 231 232export default class EntryAbility extends UIAbility { 233 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 234 let wantAgentInfo : wantAgent.WantAgentInfo = { 235 wants: [ 236 { 237 bundleName: "com.example.myapplication", 238 abilityName: "EntryAbility" 239 } 240 ], 241 operationType: wantAgent.OperationType.START_ABILITY, 242 requestCode: 0, 243 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 244 }; 245 246 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => { 247 backgroundTaskManager.startBackgroundRunning(this.context, 248 backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) 249 }); 250 } 251}; 252``` 253 254## backgroundTaskManager.startBackgroundRunning<sup>8+</sup> 255 256startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void> 257 258Requests a continuous task from the system. This API uses a promise to return the result. 259 260**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING 261 262**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 263 264**Parameters** 265 266| Name | Type | Mandatory| Description | 267| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | 268| 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).| 269| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | 270| wantAgent | [WantAgent](../apis-ability-kit/js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | 271 272**Return value** 273 274| Type | Description | 275| -------------- | ---------------- | 276| Promise\<void> | Promise used to return the result.| 277 278**Example** 279 280FA model (JS code is required for development): 281 282```js 283import backgroundTaskManager from '@ohos.backgroundTaskManager'; 284import featureAbility from '@ohos.ability.featureAbility'; 285import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; 286import { BusinessError } from '@ohos.base'; 287 288let wantAgentInfo : wantAgent.WantAgentInfo = { 289 wants: [ 290 { 291 bundleName: "com.example.myapplication", 292 abilityName: "EntryAbility" 293 } 294 ], 295 operationType: wantAgent.OperationType.START_ABILITY, 296 requestCode: 0, 297 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 298}; 299 300wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { 301 backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), 302 backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { 303 console.info("Operation startBackgroundRunning succeeded"); 304 }).catch((err: BusinessError) => { 305 console.error("Operation startBackgroundRunning failed Cause: " + err); 306 }); 307}); 308``` 309 310Stage model: 311 312```ts 313import UIAbility from '@ohos.app.ability.UIAbility'; 314import backgroundTaskManager from '@ohos.backgroundTaskManager'; 315import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; 316import Want from '@ohos.app.ability.Want'; 317import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 318import { BusinessError } from '@ohos.base'; 319 320export default class EntryAbility extends UIAbility { 321 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 322 let wantAgentInfo : wantAgent.WantAgentInfo = { 323 wants: [ 324 { 325 bundleName: "com.example.myapplication", 326 abilityName: "EntryAbility" 327 } 328 ], 329 // Type of the operation to perform after the notification is clicked. 330 operationType: wantAgent.OperationType.START_ABILITY, 331 requestCode: 0, 332 // Execution attribute of the operation to perform after the notification is clicked. 333 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 334 }; 335 336 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => { 337 backgroundTaskManager.startBackgroundRunning(this.context, 338 backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { 339 console.info("Operation startBackgroundRunning succeeded"); 340 }).catch((err: BusinessError) => { 341 console.error("Operation startBackgroundRunning failed Cause: " + err); 342 }); 343 }); 344 } 345}; 346``` 347 348## backgroundTaskManager.stopBackgroundRunning<sup>8+</sup> 349 350stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void 351 352Requests to cancel a continuous task. This API uses an asynchronous callback to return the result. 353 354**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 355 356**Parameters** 357 358| Name | Type | Mandatory | Description | 359| -------- | ------------------------- | ---- | ---------------------------------------- | 360| 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).| 361| callback | AsyncCallback<void> | Yes | Callback used to return the result. | 362 363**Example** 364 365FA model (JS code is required for development): 366 367```js 368import backgroundTaskManager from '@ohos.backgroundTaskManager'; 369import featureAbility from '@ohos.ability.featureAbility'; 370import { BusinessError } from '@ohos.base'; 371 372function callback(err: BusinessError, data: void) { 373 if (err) { 374 console.error("Operation stopBackgroundRunning failed Cause: " + err); 375 } else { 376 console.info("Operation stopBackgroundRunning succeeded"); 377 } 378} 379 380backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), callback); 381 382``` 383 384Stage model: 385 386```ts 387import UIAbility from '@ohos.app.ability.UIAbility'; 388import backgroundTaskManager from '@ohos.backgroundTaskManager'; 389import Want from '@ohos.app.ability.Want'; 390import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 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 401export default class EntryAbility extends UIAbility { 402 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 403 backgroundTaskManager.stopBackgroundRunning(this.context, callback); 404 } 405}; 406``` 407 408## backgroundTaskManager.stopBackgroundRunning<sup>8+</sup> 409 410stopBackgroundRunning(context: Context): Promise<void> 411 412Requests to cancel a continuous task. This API uses a promise to return the result. 413 414**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 415 416**Parameters** 417 418| Name | Type | Mandatory | Description | 419| ------- | ------- | ---- | ---------------------------------------- | 420| 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).| 421 422**Return value** 423 424| Type | Description | 425| -------------- | ---------------- | 426| Promise\<void> | Promise used to return the result.| 427 428**Example** 429 430FA model: 431 432```js 433import backgroundTaskManager from '@ohos.backgroundTaskManager'; 434import featureAbility from '@ohos.ability.featureAbility'; 435import { BusinessError } from '@ohos.base'; 436 437// Cancel a continuous task. 438backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { 439 console.info("Operation stopBackgroundRunning succeeded"); 440}).catch((err: BusinessError) => { 441 console.error("Operation stopBackgroundRunning failed Cause: " + err); 442}); 443 444``` 445 446Stage model: 447 448```ts 449import UIAbility from '@ohos.app.ability.UIAbility'; 450import backgroundTaskManager from '@ohos.backgroundTaskManager'; 451import Want from '@ohos.app.ability.Want'; 452import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 453import { BusinessError } from '@ohos.base'; 454 455export default class EntryAbility extends UIAbility { 456 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 457 // Cancel a continuous task. 458 backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { 459 console.info("Operation stopBackgroundRunning succeeded"); 460 }).catch((err: BusinessError) => { 461 console.error("Operation stopBackgroundRunning failed Cause: " + err); 462 }); 463 } 464}; 465``` 466 467## DelaySuspendInfo 468 469Provides the information about the suspension delay. 470 471**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask 472 473| Name | Type | Mandatory | Description | 474| --------------- | ------ | ---- | ---------------------------------------- | 475| requestId | number | Yes | ID of the suspension delay request. | 476| actualDelayTime | number | Yes | Actual suspension delay duration of the application, in milliseconds.<br>The default duration is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.| 477 478 479## BackgroundMode<sup>8+</sup> 480 481**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask 482 483| Name | Value | Description | 484| ----------------------- | ---- | --------------------- | 485| DATA_TRANSFER | 1 | Data transfer. | 486| AUDIO_PLAYBACK | 2 | Audio playback. | 487| AUDIO_RECORDING | 3 | Audio recording. | 488| LOCATION | 4 | Positioning and navigation. | 489| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | 490| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | 491| TASK_KEEPING | 9 | Computing task (effective only for specific devices). | 492