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