1# @ohos.resourceschedule.backgroundTaskManager (Background Task Management)
2
3The **backgroundTaskManager** module provides APIs to request background tasks. You can use the APIs to request transient tasks, continuous tasks, or efficiency resources to prevent the application process from being terminated or suspended when your application is switched to the background.
4
5>  **NOTE**
6>
7> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8
9
10## Modules to Import
11
12```ts
13import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
14```
15
16## backgroundTaskManager.requestSuspendDelay
17
18requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspendInfo
19
20Requests a transient task.
21
22>  **NOTE**
23>
24> The maximum duration of a transient task is 3 minutes in normal cases. In the case of a [low battery](../apis-basic-services-kit/js-apis-battery-info.md), the maximum duration is decreased to 1 minute.
25
26**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
27
28**Parameters**
29
30| Name     | Type                  | Mandatory  | Description                            |
31| -------- | -------------------- | ---- | ------------------------------ |
32| reason   | string               | Yes   | Reason for requesting the transient task.                    |
33| callback | Callback<void> | Yes   | Callback used to notify the application that the transient task is about to time out. Generally, the callback is invoked 6 seconds before the timeout.|
34
35**Return value**
36
37| Type                                   | Description       |
38| ------------------------------------- | --------- |
39| [DelaySuspendInfo](#delaysuspendinfo) | Information about the transient task.|
40
41**Error codes**
42
43For details about the error codes, see [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md) and [Universal Error Codes](../errorcode-universal.md).
44
45| ID  | Error Message|
46| --------- | ------- |
47| 401    | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. |
48| 9800001 | Memory operation failed. |
49| 9800002 | Parcel operation failed. |
50| 9800003 | Internal transaction failed. |
51| 9800004 | System service operation failed. |
52| 9900001 | Caller information verification failed for a transient task. |
53| 9900002 | Transient task verification failed. |
54
55**Example**
56
57```ts
58import { BusinessError } from '@kit.BasicServicesKit';
59
60let myReason = 'test requestSuspendDelay';
61try {
62    let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
63        console.info("Request suspension delay will time out.");
64    })
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} catch (error) {
70    console.error(`requestSuspendDelay failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
71}
72```
73
74
75## backgroundTaskManager.getRemainingDelayTime
76
77getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void
78
79Obtains the remaining time of a transient task. This API uses an asynchronous callback to return the result.
80
81**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
82
83**Parameters**
84
85| Name      | Type                         | Mandatory  | Description                                      |
86| --------- | --------------------------- | ---- | ---------------------------------------- |
87| requestId | number                      | Yes   | Request ID of the transient task.                              |
88| callback  | AsyncCallback<number> | Yes   | Callback used to return the remaining time, in milliseconds.|
89
90**Error codes**
91
92For details about the error codes, see [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md) and [Universal Error Codes](../errorcode-universal.md).
93
94| ID  | Error Message|
95| --------- | ------- |
96| 401    | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. |
97| 9800001 | Memory operation failed. |
98| 9800002 | Parcel operation failed. |
99| 9800003 | Internal transaction failed. |
100| 9800004 | System service operation failed. |
101| 9900001 | Caller information verification failed for a transient task. |
102| 9900002 | Transient task verification failed. |
103
104
105**Example**
106
107```ts
108import { BusinessError } from '@kit.BasicServicesKit';
109
110let id = 1;
111backgroundTaskManager.getRemainingDelayTime(id, (error: BusinessError, res: number) => {
112    if(error) {
113        console.error(`callback => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`);
114    } else {
115        console.log('callback => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
116    }
117})
118```
119
120
121## backgroundTaskManager.getRemainingDelayTime
122
123getRemainingDelayTime(requestId: number): Promise<number>
124
125Obtains the remaining time of a transient task. This API uses a promise to return the result.
126
127**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
128
129**Parameters**
130
131| Name      | Type    | Mandatory  | Description        |
132| --------- | ------ | ---- | ---------- |
133| requestId | number | Yes   | Request ID of the transient task.|
134
135**Return value**
136
137| Type                   | Description                                      |
138| --------------------- | ---------------------------------------- |
139| Promise<number> | Promise used to return the remaining time, in milliseconds.|
140
141**Error codes**
142
143For details about the error codes, see [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md) and [Universal Error Codes](../errorcode-universal.md).
144
145| ID  | Error Message|
146| --------- | ------- |
147| 401    | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. |
148| 9800001 | Memory operation failed. |
149| 9800002 | Parcel operation failed. |
150| 9800003 | Internal transaction failed. |
151| 9800004 | System service operation failed. |
152| 9900001 | Caller information verification failed for a transient task. |
153| 9900002 | Transient task verification failed. |
154
155**Example**
156
157```ts
158import { BusinessError } from '@kit.BasicServicesKit';
159
160let id = 1;
161backgroundTaskManager.getRemainingDelayTime(id).then((res: number) => {
162    console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
163}).catch((error: BusinessError) => {
164    console.error(`promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`);
165})
166```
167
168
169## backgroundTaskManager.cancelSuspendDelay
170
171cancelSuspendDelay(requestId: number): void
172
173Cancels a transient task.
174
175**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
176
177**Parameters**
178
179| Name      | Type    | Mandatory  | Description        |
180| --------- | ------ | ---- | ---------- |
181| requestId | number | Yes   | Request ID of the transient task.|
182
183**Error codes**
184
185For details about the error codes, see [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md) and [Universal Error Codes](../errorcode-universal.md).
186
187| ID  | Error Message|
188| --------- | ------- |
189| 401    | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. |
190| 9800001 | Memory operation failed. |
191| 9800002 | Parcel operation failed. |
192| 9800003 | Internal transaction failed. |
193| 9800004 | System service operation failed. |
194| 9900001 | Caller information verification failed for a transient task. |
195| 9900002 | Transient task verification failed. |
196
197**Example**
198
199  ```js
200  import { BusinessError } from '@kit.BasicServicesKit';
201
202  let id = 1;
203  try {
204    backgroundTaskManager.cancelSuspendDelay(id);
205  } catch (error) {
206    console.error(`cancelSuspendDelay failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
207  }
208  ```
209
210## backgroundTaskManager.startBackgroundRunning
211
212startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void
213
214Requests a continuous task. This API uses an asynchronous callback to return the result.
215
216**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING
217
218**Atomic service API**: This API can be used in atomic services since API version 12.
219
220**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
221
222**Parameters**
223
224| Name      | Type                                | Mandatory  | Description                                      |
225| --------- | ---------------------------------- | ---- | ---------------------------------------- |
226| 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).|
227| bgMode    | [BackgroundMode](#backgroundmode) | Yes   | Continuous task mode.                             |
228| wantAgent | [WantAgent](../apis-ability-kit/js-apis-app-ability-wantAgent.md) | Yes   | Notification parameters, which are used to specify the target page that is redirected to when a continuous task notification is clicked.          |
229| callback  | AsyncCallback&lt;void&gt;          | Yes   | Callback used to return the result. If the continuous task is requested, **err** is **undefined**. Otherwise, **err** is an error object.   |
230
231**Error codes**
232
233For details about the error codes, see [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md) and [Universal Error Codes](../errorcode-universal.md).
234
235| ID | Error Message            |
236| ---- | --------------------- |
237| 201 | Permission denied. |
238| 202 | Not System App. |
239| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | 
240| 9800001 | Memory operation failed. |
241| 9800002 | Parcel operation failed. |
242| 9800003 | Internal transaction failed. | 
243| 9800004 | System service operation failed. |
244| 9800005 | Continuous task verification failed. |
245| 9800006 | Notification verification failed for a continuous task. |
246| 9800007 | Continuous task storage failed. |
247
248**Example**
249
250```js
251import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
252import { BusinessError } from '@kit.BasicServicesKit';
253import { wantAgent, WantAgent } from '@kit.AbilityKit';
254import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
255
256function callback(error: BusinessError, data: void) {
257    if (error) {
258        console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
259    } else {
260        console.info("Operation startBackgroundRunning succeeded");
261    }
262}
263
264export default class EntryAbility extends UIAbility {
265    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
266        let wantAgentInfo: wantAgent.WantAgentInfo = {
267            // List of operations to be executed after the notification is clicked.
268            wants: [
269                {
270                    bundleName: "com.example.myapplication",
271                    abilityName: "EntryAbility"
272                }
273            ],
274            // Type of the operation to perform after the notification is clicked.
275            actionType: wantAgent.OperationType.START_ABILITY,
276            // Custom request code.
277            requestCode: 0,
278            // Execution attribute of the operation to perform after the notification is clicked.
279            wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
280        };
281
282        try {
283            // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
284            wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => {
285                try {
286                    backgroundTaskManager.startBackgroundRunning(this.context,
287                        backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback)
288                } catch (error) {
289                    console.error(`Operation startBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
290                }
291            });
292        } catch (error) {
293            console.error(`Operation getWantAgent failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
294        }
295    }
296};
297```
298
299## backgroundTaskManager.startBackgroundRunning
300
301startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise&lt;void&gt;
302
303Requests a continuous task. This API uses a promise to return the result.
304
305**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING
306
307**Atomic service API**: This API can be used in atomic services since API version 12.
308
309**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
310
311**Parameters**
312
313| Name      | Type                                | Mandatory  | Description                                      |
314| --------- | ---------------------------------- | ---- | ---------------------------------------- |
315| 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).|
316| bgMode    | [BackgroundMode](#backgroundmode) | Yes   | Continuous task mode.                             |
317| wantAgent | [WantAgent](../apis-ability-kit/js-apis-app-ability-wantAgent.md) | Yes   | Notification parameters, which are used to specify the target page that is redirected to when a continuous task notification is clicked.                |
318
319**Return value**
320
321| Type            | Description              |
322| -------------- | ---------------- |
323| Promise\<void> | Promise that returns no value.|
324
325**Error codes**
326
327For details about the error codes, see [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md) and [Universal Error Codes](../errorcode-universal.md).
328
329| ID | Error Message            |
330| ---- | --------------------- |
331| 201 | Permission denied. |
332| 202 | Not System App. |
333| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | 
334| 9800001 | Memory operation failed. |
335| 9800002 | Parcel operation failed. |
336| 9800003 | Internal transaction failed. |
337| 9800004 | System service operation failed. |
338| 9800005 | Continuous task verification failed. |
339| 9800006 | Notification verification failed for a continuous task. |
340| 9800007 | Continuous task storage failed. |
341
342**Example**
343
344```js
345import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
346import { BusinessError } from '@kit.BasicServicesKit';
347import { wantAgent, WantAgent } from '@kit.AbilityKit';
348import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
349
350export default class EntryAbility extends UIAbility {
351    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
352        let wantAgentInfo: wantAgent.WantAgentInfo = {
353            // List of operations to be executed after the notification is clicked.
354            wants: [
355                {
356                    bundleName: "com.example.myapplication",
357                    abilityName: "EntryAbility"
358                }
359            ],
360            // Type of the operation to perform after the notification is clicked.
361            actionType: wantAgent.OperationType.START_ABILITY,
362            // Custom request code.
363            requestCode: 0,
364            // Execution attribute of the operation to perform after the notification is clicked.
365            wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
366        };
367
368        try {
369            // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
370            wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => {
371                try {
372                    backgroundTaskManager.startBackgroundRunning(this.context,
373                        backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => {
374                        console.info("Operation startBackgroundRunning succeeded");
375                    }).catch((error: BusinessError) => {
376                        console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
377                    });
378                } catch (error) {
379                    console.error(`Operation startBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
380                }
381            });
382        } catch (error) {
383            console.error(`Operation getWantAgent failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
384        }
385    }
386};
387```
388
389## backgroundTaskManager.stopBackgroundRunning
390
391stopBackgroundRunning(context: Context, callback: AsyncCallback&lt;void&gt;): void
392
393Cancels a continuous task. This API uses an asynchronous callback to return the result.
394
395**Atomic service API**: This API can be used in atomic services since API version 12.
396
397**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
398
399**Parameters**
400
401| Name     | Type                       | Mandatory  | Description                                      |
402| -------- | ------------------------- | ---- | ---------------------------------------- |
403| 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).|
404| callback | AsyncCallback&lt;void&gt; | Yes   | Callback used to return the result. If the continuous task is canceled, **err** is **undefined**. Otherwise, **err** is an error object.|
405
406**Error codes**
407
408For details about the error codes, see [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md) and [Universal Error Codes](../errorcode-universal.md).
409
410| ID | Error Message            |
411| ---- | --------------------- |
412| 201 | Permission denied. |
413| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. |
414| 9800001 | Memory operation failed. |
415| 9800002 | Parcel operation failed. |
416| 9800003 | Internal transaction failed. |
417| 9800004 | System service operation failed. |
418| 9800005 | Continuous task verification failed. |
419| 9800006 | Notification verification failed for a continuous task. |
420| 9800007 | Continuous task storage failed. |
421
422**Example**
423
424```js
425import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
426import { BusinessError } from '@kit.BasicServicesKit';
427import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
428
429function callback(error: BusinessError, data: void) {
430    if (error) {
431        console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
432    } else {
433        console.info("Operation stopBackgroundRunning succeeded");
434    }
435}
436
437export default class EntryAbility extends UIAbility {
438    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
439        try {
440            backgroundTaskManager.stopBackgroundRunning(this.context, callback);
441        } catch (error) {
442            console.error(`Operation stopBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
443        }
444    }
445};
446```
447
448## backgroundTaskManager.stopBackgroundRunning
449
450stopBackgroundRunning(context: Context): Promise&lt;void&gt;
451
452Cancels a continuous task. This API uses a promise to return the result.
453
454**Atomic service API**: This API can be used in atomic services since API version 12.
455
456**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
457
458**Parameters**
459
460| Name    | Type     | Mandatory  | Description                                      |
461| ------- | ------- | ---- | ---------------------------------------- |
462| 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).|
463
464**Return value**
465
466| Type            | Description              |
467| -------------- | ---------------- |
468| Promise\<void> | Promise that returns no value.|
469
470**Error codes**
471
472For details about the error codes, see [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md) and [Universal Error Codes](../errorcode-universal.md).
473
474| ID | Error Message            |
475| ---- | --------------------- |
476| 201 | Permission denied. |
477| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. |
478| 9800001 | Memory operation failed. |
479| 9800002 | Parcel operation failed. |
480| 9800003 | Internal transaction failed. |
481| 9800004 | System service operation failed. |
482| 9800005 | Continuous task verification failed. |
483| 9800006 | Notification verification failed for a continuous task. |
484| 9800007 | Continuous task storage failed. |
485
486**Example**
487
488```js
489import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
490import { BusinessError } from '@kit.BasicServicesKit';
491import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
492
493export default class EntryAbility extends UIAbility {
494    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
495        try {
496            backgroundTaskManager.stopBackgroundRunning(this.context).then(() => {
497                console.info("Operation stopBackgroundRunning succeeded");
498            }).catch((error: BusinessError) => {
499                console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
500            });
501        } catch (error) {
502            console.error(`Operation stopBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
503        }
504    }
505};
506```
507
508## backgroundTaskManager.startBackgroundRunning<sup>12+</sup>
509
510startBackgroundRunning(context: Context, bgModes: string[], wantAgent: WantAgent): Promise&lt;ContinuousTaskNotification&gt;
511
512Requests a continuous task. This API uses a promise to return the result.
513
514**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING
515
516**Atomic service API**: This API can be used in atomic services since API version 12.
517
518**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
519
520**Parameters**
521
522| Name      | Type                                | Mandatory  | Description                                      |
523| --------- | ---------------------------------- | ---- | ---------------------------------------- |
524| context   | [Context](../apis-ability-kit/js-apis-inner-application-context.md)                            | Yes   | Application context.|
525| bgModes    | string[] | Yes   | Continuous task mode. The options are as follows:<br>**dataTransfer**: data transfer.<br>**audioPlayback**: audio playback.<br>**audioRecording**: audio recording.<br>**location**: location and navigation.<br>**bluetoothInteraction**: Bluetooth-related task<br>**multiDeviceConnection**: multi-device connection.<br>One or more modes can be passed in.|
526| wantAgent | [WantAgent](../apis-ability-kit/js-apis-app-ability-wantAgent.md) | Yes   | Notification parameters, which are used to specify the target page that is redirected to when a continuous task notification is clicked.                |
527
528**Return value**
529
530| Type            | Description              |
531| -------------- | ---------------- |
532| Promise\<ContinuousTaskNotification> | Promise that returns a [continuous-task notification](#continuoustasknotification12).|
533
534**Error codes**
535
536For details about the error codes, see [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md) and [Universal Error Codes](../errorcode-universal.md).
537
538| ID | Error Message            |
539| ---- | --------------------- |
540| 201 | Permission denied. |
541| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. |
542| 9800001 | Memory operation failed. |
543| 9800002 | Parcel operation failed. |
544| 9800003 | Internal transaction failed. |
545| 9800004 | System service operation failed. |
546| 9800005 | Continuous task verification failed. |
547| 9800006 | Notification verification failed for a continuous task. |
548| 9800007 | Continuous task storage failed. |
549
550**Example**
551
552```js
553import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
554import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
555import { window } from '@kit.ArkUI';
556import { BusinessError } from '@kit.BasicServicesKit';
557import { wantAgent, WantAgent } from '@kit.AbilityKit';
558import { notificationManager } from '@kit.NotificationKit';
559
560export default class EntryAbility extends UIAbility {
561  id: number = 0; // Save the notification ID.
562
563  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
564    let wantAgentInfo: wantAgent.WantAgentInfo = {
565      // List of operations to be executed after the notification is clicked.
566      wants: [
567        {
568          bundleName: "com.example.myapplication",
569          abilityName: "EntryAbility"
570        }
571      ],
572      // Type of the operation to perform after the notification is clicked.
573      actionType: wantAgent.OperationType.START_ABILITY,
574      // Custom request code.
575      requestCode: 0,
576      // Execution attribute of the operation to perform after the notification is clicked.
577      wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
578    };
579
580    try {
581      // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
582      wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => {
583        try {
584          let list: Array<string> = ["dataTransfer"];
585          backgroundTaskManager.startBackgroundRunning(this.context, list, wantAgentObj).then((res: backgroundTaskManager.ContinuousTaskNotification) => {
586            console.info("Operation startBackgroundRunning succeeded");
587            // For a continuous task of the upload and download type, the application can use the notification ID returned in res to update the notification, for example, sending a template notification with a progress bar.
588            this.id = res.notificationId;
589          }).catch((error: BusinessError) => {
590            console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
591          });
592        } catch (error) {
593          console.error(`Operation startBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
594        }
595      });
596    } catch (error) {
597      console.error(`Operation getWantAgent failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
598    }
599  }
600
601  updateProcess(process: Number) {
602    // The application defines the download notification template.
603    let downLoadTemplate: notificationManager.NotificationTemplate = {
604      name: 'downloadTemplate', // Currently, only downloadTemplate is supported. Retain the value.
605      data: {
606        title:'File download: music.mp4', // Mandatory.
607        fileName: 'senTemplate', // Mandatory.
608        progressValue: process, // The application updates the progress, which is user-defined.
609      }
610    };
611    let request: notificationManager.NotificationRequest = {
612      content: {
613        // System live view type, which remains unchanged.
614        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW,
615        systemLiveView: {
616          typeCode: 8, // Set this parameter to 8 for the upload and download type. Currently, only the upload and download type is supported. Retain the value.
617          title: "test", // Customized by the application.
618          text: "test", // Customized by the application.
619        }
620      },
621      id: this.id, // The value must be the ID returned for a continuous-task request. Otherwise, the application fails to update the notification.
622      notificationSlotType: notificationManager.SlotType.LIVE_VIEW, // Live view type. Retain the value.
623      template: downLoadTemplate // Name of the template to be set for the application.
624    };
625
626    try {
627      notificationManager.publish(request).then(() => {
628        console.info("publish success, id= " + this.id);
629      }).catch((err: BusinessError) => {
630        console.error(`publish fail: ${JSON.stringify(err)}`);
631      });
632    } catch (err) {
633      console.error(`publish fail: ${JSON.stringify(err)}`);
634    }
635  }
636};
637```
638## backgroundTaskManager.updateBackgroundRunning<sup>12+</sup>
639
640updateBackgroundRunning(context: Context, bgModes: string[]): Promise&lt;ContinuousTaskNotification&gt;
641
642Updates a continuous task. This API uses a promise to return the result.
643
644**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING
645
646**Atomic service API**: This API can be used in atomic services since API version 12.
647
648**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
649
650**Parameters**
651
652| Name      | Type                                | Mandatory  | Description                                      |
653| --------- | ---------------------------------- | ---- | ---------------------------------------- |
654| context   | [Context](../apis-ability-kit/js-apis-inner-application-context.md)                            | Yes   | Application context.|
655| bgModes    | string[] | Yes   | Continuous task mode. The options are as follows:<br>**dataTransfer**: data transfer.<br>**audioPlayback**: audio playback.<br>**audioRecording**: audio recording.<br>**location**: location and navigation.<br>**bluetoothInteraction**: Bluetooth-related task<br>**multiDeviceConnection**: multi-device connection.<br>One or more modes can be passed in.
656
657**Return value**
658
659| Type            | Description              |
660| -------------- | ---------------- |
661| Promise\<ContinuousTaskNotification> | Promise that returns a [continuous-task notification](#continuoustasknotification12).|
662
663**Error codes**
664
665For details about the error codes, see [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md) and [Universal Error Codes](../errorcode-universal.md).
666
667| ID | Error Message            |
668| ---- | --------------------- |
669| 201 | Permission denied. |
670| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. |
671| 9800001 | Memory operation failed. |
672| 9800002 | Parcel operation failed. |
673| 9800003 | Internal transaction failed. |
674| 9800004 | System service operation failed. |
675| 9800005 | Continuous task verification failed. |
676| 9800006 | Notification verification failed for a continuous task. |
677| 9800007 | Continuous task storage failed. |
678
679**Example**
680
681```js
682import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
683import { BusinessError } from '@kit.BasicServicesKit';
684import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
685
686export default class EntryAbility extends UIAbility {
687    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
688        try {
689                try {
690                    // You must call startBackgroundRunning before updateBackgroundRunning. Here it is assumed that you have called startBackgroundRunning.
691                    let list: Array<string> = ["audioPlayback"];
692                    backgroundTaskManager.updateBackgroundRunning(this.context, list).then(() => {
693                        console.info("Operation updateBackgroundRunning succeeded");
694                    }).catch((error: BusinessError) => {
695                        console.error(`Operation updateBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
696                    });
697                } catch (error) {
698                    console.error(`Operation startBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
699                }
700        } catch (error) {
701            console.error(`Operation getWantAgent failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
702        }
703    }
704};
705```
706
707## DelaySuspendInfo
708
709Defines the information about the transient task.
710
711**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
712
713| Name            | Type    | Mandatory  | Description                                      |
714| --------------- | ------ | ---- | ---------------------------------------- |
715| requestId       | number | Yes   | Request ID of the transient task.                              |
716| actualDelayTime | number | Yes   | Actual duration of the transient task that the application requests, in milliseconds.<br>The maximum duration of a transient task is 3 minutes in normal cases. In the case of a [low battery](../apis-basic-services-kit/js-apis-battery-info.md), the maximum duration is decreased to 1 minute.|
717
718## BackgroundMode
719
720Enumerates the continuous task modes.
721
722**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
723
724| Name                    | Value | Description                   |
725| ----------------------- | ---- | --------------------- |
726| DATA_TRANSFER           | 1    | Data transfer.                 |
727| AUDIO_PLAYBACK          | 2    | Audio playback.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                 |
728| AUDIO_RECORDING         | 3    | Audio recording.                   |
729| LOCATION                | 4    | Positioning and navigation.                 |
730| BLUETOOTH_INTERACTION   | 5    | Bluetooth-related task.                 |
731| MULTI_DEVICE_CONNECTION | 6    | Multi-device connection.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                |
732| VOIP<sup>13+</sup> | 8    | Audio and video calls.                |
733| TASK_KEEPING            | 9    | Computing task (for specific devices only).       |
734
735## ContinuousTaskNotification<sup>12+</sup>
736
737Describes the information about a continuous-task notification.
738
739**Atomic service API**: This API can be used in atomic services since API version 12.
740
741**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
742
743| Name            | Type    | Mandatory  | Description                                      |
744| --------------- | ------ | ---- | ---------------------------------------- |
745| slotType       | [notificationManager.SlotType](../apis-notification-kit/js-apis-notificationManager.md#slottype) | Yes   | Slot type of a continuous-task notification.|
746| contentType | [notificationManager.ContentType](../apis-notification-kit/js-apis-notificationManager.md#contenttype) | Yes   | Content type of a continuous-task notification.|
747| notificationId | number | Yes   | ID of the continuous-task notification.|
748