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