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