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