• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# BackgroundTaskManager
2
3This module provides background task management.
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 or continuous task for delayed suspension based on the service type.
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> **NOTE**
12>
13> 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.
14
15
16## Modules to Import
17
18```
19import backgroundTaskManager from '@ohos.backgroundTaskManager';
20```
21
22
23## backgroundTaskManager.requestSuspendDelay
24
25requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspendInfo
26
27Requests delayed suspension after the application switches to the background.
28
29The default duration of delayed suspension 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.
30
31**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
32
33**Parameters**
34| Name     | Type                  | Mandatory  | Description                            |
35| -------- | -------------------- | ---- | ------------------------------ |
36| reason   | string               | Yes   | Reason for delayed transition to the suspended state.                    |
37| 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.|
38
39**Return value**
40| Type                                   | Description       |
41| ------------------------------------- | --------- |
42| [DelaySuspendInfo](#delaysuspendinfo) | Information about the suspension delay.|
43
44**Example**
45
46  ```js
47  let myReason = 'test requestSuspendDelay';
48  let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
49      console.info("Request suspension delay will time out.");
50  })
51
52  var id = delayInfo.requestId;
53  var time = delayInfo.actualDelayTime;
54  console.info("The requestId is: " + id);
55  console.info("The actualDelayTime is: " + time);
56  ```
57
58
59## backgroundTaskManager.getRemainingDelayTime
60
61getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void
62
63Obtains the remaining duration before the application is suspended. This API uses an asynchronous callback to return the result.
64
65**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
66
67**Parameters**
68| Name      | Type                         | Mandatory  | Description                                      |
69| --------- | --------------------------- | ---- | ---------------------------------------- |
70| requestId | number                      | Yes   | ID of the suspension delay request.                              |
71| callback  | AsyncCallback<number> | Yes   | Callback used to return the remaining duration before the application is suspended, in milliseconds.|
72
73**Example**
74
75  ```js
76  let id = 1;
77  backgroundTaskManager.getRemainingDelayTime(id, (err, res) => {
78      if(err) {
79          console.log('callback => Operation getRemainingDelayTime failed. Cause: ' + err.code);
80      } else {
81          console.log('callback => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
82      }
83  })
84  ```
85
86
87## backgroundTaskManager.getRemainingDelayTime
88
89getRemainingDelayTime(requestId: number): Promise<number>
90
91Obtains the remaining duration before the application is suspended. This API uses a promise to return the result.
92
93**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
94
95**Parameters**
96| Name      | Type    | Mandatory  | Description        |
97| --------- | ------ | ---- | ---------- |
98| requestId | number | Yes   | ID of the suspension delay request.|
99
100**Return value**
101| Type                   | Description                                      |
102| --------------------- | ---------------------------------------- |
103| Promise<number> | Promise used to return the remaining duration before the application is suspended, in milliseconds.|
104
105**Example**
106  ```js
107  let id = 1;
108  backgroundTaskManager.getRemainingDelayTime(id).then( res => {
109      console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
110  }).catch( err => {
111      console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code);
112  })
113  ```
114
115
116## backgroundTaskManager.cancelSuspendDelay
117
118cancelSuspendDelay(requestId: number): void
119
120Cancels the suspension delay.
121
122**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
123
124**Parameters**
125| Name      | Type    | Mandatory  | Description        |
126| --------- | ------ | ---- | ---------- |
127| requestId | number | Yes   | ID of the suspension delay request.|
128
129**Example**
130  ```js
131  let id = 1;
132  backgroundTaskManager.cancelSuspendDelay(id);
133  ```
134
135
136## backgroundTaskManager.startBackgroundRunning<sup>8+</sup>
137
138startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback&lt;void&gt;): void
139
140Requests a continuous task from the system. This API uses an asynchronous callback to return the result.
141
142**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING
143
144**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
145
146**Parameters**
147| Name      | Type                                | Mandatory  | Description                      |
148| --------- | ---------------------------------- | ---- | ------------------------ |
149| context   | [Context](js-apis-Context.md)      | Yes   | Application context.               |
150| bgMode    | [BackgroundMode](#backgroundmode8) | Yes   | Background mode requested.             |
151| wantAgent | [WantAgent](js-apis-wantAgent.md)  | Yes   | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked.|
152| callback  | AsyncCallback&lt;void&gt;          | Yes   | Callback used to return the result.  |
153
154**Example**
155```js
156import backgroundTaskManager from '@ohos.backgroundTaskManager';
157import featureAbility from '@ohos.ability.featureAbility';
158import wantAgent from '@ohos.wantAgent';
159
160function callback(err, data) {
161    if (err) {
162        console.error("Operation startBackgroundRunning failed Cause: " + err);
163    } else {
164        console.info("Operation startBackgroundRunning succeeded");
165    }
166}
167
168let wantAgentInfo = {
169    wants: [
170        {
171            bundleName: "com.example.myapplication",
172            abilityName: "com.example.myapplication.MainAbility"
173        }
174    ],
175    operationType: wantAgent.OperationType.START_ABILITY,
176    requestCode: 0,
177    wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
178};
179
180wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
181    backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
182        backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj, callback)
183});
184
185```
186
187## backgroundTaskManager.startBackgroundRunning<sup>8+</sup>
188
189startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise&lt;void&gt;
190
191Requests a continuous task from the system. This API uses a promise to return the result.
192
193**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING
194
195**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
196
197**Parameters**
198
199| Name      | Type                                | Mandatory  | Description                     |
200| --------- | ---------------------------------- | ---- | ----------------------- |
201| context   | [Context](js-apis-Context.md)      | Yes   | Application context.              |
202| bgMode    | [BackgroundMode](#backgroundmode8) | Yes   | Background mode requested.            |
203| wantAgent | [WantAgent](js-apis-wantAgent.md)  | Yes   | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked.|
204
205**Return value**
206| Type            | Description              |
207| -------------- | ---------------- |
208| Promise\<void> | Promise used to return the result.|
209
210**Example**
211```js
212import backgroundTaskManager from '@ohos.backgroundTaskManager';
213import featureAbility from '@ohos.ability.featureAbility';
214import wantAgent from '@ohos.wantAgent';
215
216let wantAgentInfo = {
217    wants: [
218        {
219            bundleName: "com.example.myapplication",
220            abilityName: "com.example.myapplication.MainAbility"
221        }
222    ],
223    operationType: wantAgent.OperationType.START_ABILITY,
224    requestCode: 0,
225    wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
226};
227
228wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
229    backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
230        backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
231        console.info("Operation startBackgroundRunning succeeded");
232    }).catch((err) => {
233        console.error("Operation startBackgroundRunning failed Cause: " + err);
234    });
235});
236
237```
238
239## backgroundTaskManager.stopBackgroundRunning<sup>8+</sup>
240
241stopBackgroundRunning(context: Context, callback: AsyncCallback&lt;void&gt;): void
242
243Requests to cancel a continuous task. This API uses an asynchronous callback to return the result.
244
245**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
246
247**Parameters**
248| Name     | Type                           | Mandatory  | Description                    |
249| -------- | ----------------------------- | ---- | ---------------------- |
250| context  | [Context](js-apis-Context.md) | Yes   | Application context.             |
251| callback | AsyncCallback&lt;void&gt;     | Yes   | Callback used to return the result.|
252
253**Example**
254```js
255import backgroundTaskManager from '@ohos.backgroundTaskManager';
256import featureAbility from '@ohos.ability.featureAbility';
257
258function callback(err, data) {
259    if (err) {
260        console.error("Operation stopBackgroundRunning failed Cause: " + err);
261    } else {
262        console.info("Operation stopBackgroundRunning succeeded");
263    }
264}
265
266backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), callback);
267
268```
269
270## backgroundTaskManager.stopBackgroundRunning<sup>8+</sup>
271
272stopBackgroundRunning(context: Context): Promise&lt;void&gt;
273
274Requests to cancel a continuous task. This API uses a promise to return the result.
275
276**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
277
278**Parameters**
279| Name    | Type                           | Mandatory  | Description       |
280| ------- | ----------------------------- | ---- | --------- |
281| context | [Context](js-apis-Context.md) | Yes   | Application context.|
282
283**Return value**
284| Type            | Description              |
285| -------------- | ---------------- |
286| Promise\<void> | Promise used to return the result.|
287
288**Example**
289```js
290import backgroundTaskManager from '@ohos.backgroundTaskManager';
291import featureAbility from '@ohos.ability.featureAbility';
292
293backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
294    console.info("Operation stopBackgroundRunning succeeded");
295}).catch((err) => {
296    console.error("Operation stopBackgroundRunning failed Cause: " + err);
297});
298
299```
300
301## DelaySuspendInfo
302
303Provides the information about the suspension delay.
304
305**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
306
307| Name            | Type    | Mandatory  | Description                                      |
308| --------------- | ------ | ---- | ---------------------------------------- |
309| requestId       | number | Yes   | ID of the suspension delay request.                              |
310| 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.|
311
312
313## BackgroundMode<sup>8+</sup>
314
315**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
316
317| Name                 | Value| Description                                                        |
318| ----------------------- | ------ | ------------------------------------------------------------ |
319| DATA_TRANSFER           | 1      | Data transfer.                                                    |
320| AUDIO_PLAYBACK          | 2      | Audio playback.                                                    |
321| AUDIO_RECORDING         | 3      | Audio recording.                                                        |
322| LOCATION                | 4      | Positioning and navigation.                                                    |
323| BLUETOOTH_INTERACTION   | 5      | Bluetooth-related task.                                                    |
324| MULTI_DEVICE_CONNECTION | 6      | Multi-device connection.                                                  |
325| WIFI_INTERACTION        | 7      | WLAN-related.<br>This is a system API and cannot be called by third-party applications.|
326| VOIP                    | 8      | Audio and video calls.<br>This is a system API and cannot be called by third-party applications.|
327| TASK_KEEPING            | 9      | Computing task (effective only for specific devices).                                |
328