• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.resourceschedule.backgroundTaskManager (Background Task Management) (System API)
2
3<!--Kit: Background Tasks Kit-->
4<!--Subsystem: ResourceSchedule-->
5<!--Owner: @cheng-shichang-->
6<!--Designer: @zhouben25-->
7<!--Tester: @fenglili18-->
8<!--Adviser: @Brilliantry_Rui-->
9
10The **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.
11
12>  **NOTE**
13>
14> - 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.
15>
16> - This topic describes only system APIs provided by the module. For details about its public APIs, see [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](js-apis-resourceschedule-backgroundTaskManager.md).
17
18## Modules to Import
19
20```ts
21import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
22```
23
24## backgroundTaskManager.applyEfficiencyResources
25
26applyEfficiencyResources(request: EfficiencyResourcesRequest): void
27
28Requests efficiency resources.
29
30**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply
31
32**System API**: This is a system API.
33
34**Parameters**
35
36| Name    | Type     | Mandatory  | Description                                      |
37| ------- | ------- | ---- | ---------------------------------------- |
38| request | [EfficiencyResourcesRequest](#efficiencyresourcesrequest) | Yes   | Necessary information carried in the request, including the resource type and timeout interval.|
39
40
41**Error codes**
42
43For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md).
44
45| ID | Error Message            |
46| ---- | --------------------- |
47| 201 | Permission denied. |
48| 202 | Not System App. |
49| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. |
50| 9800001 | Memory operation failed. |
51| 9800002 | Failed to write data into parcel. Possible reasons: 1. Invalid parameters; 2. Failed to apply for memory. |
52| 9800003 | Internal transaction failed. |
53| 9800004 | System service operation failed. |
54| 18700001 | Caller information verification failed for an energy resource request. |
55
56**Example**
57
58```js
59import { BusinessError } from '@kit.BasicServicesKit';
60
61let request: backgroundTaskManager.EfficiencyResourcesRequest = {
62    resourceTypes: backgroundTaskManager.ResourceType.CPU,
63    isApply: true,
64    timeOut: 0,
65    reason: "apply",
66    isPersist: true,
67    isProcess: false,
68};
69try {
70    backgroundTaskManager.applyEfficiencyResources(request);
71    console.info("applyEfficiencyResources success. ");
72} catch (error) {
73    console.error(`applyEfficiencyResources failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
74}
75```
76
77## backgroundTaskManager.resetAllEfficiencyResources
78
79resetAllEfficiencyResources(): void
80
81Releases all efficiency resources.
82
83**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply
84
85**System API**: This is a system API.
86
87**Error codes**
88
89For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md).
90
91| ID | Error Message            |
92| ---- | --------------------- |
93| 201 | Permission denied. |
94| 202 | Not System App. |
95| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. |
96| 9800001 | Memory operation failed. |
97| 9800002 | Failed to write data into parcel. Possible reasons: 1. Invalid parameters; 2. Failed to apply for memory. |
98| 9800003 | Internal transaction failed. |
99| 9800004 | System service operation failed. |
100| 18700001 | Caller information verification failed for an energy resource request. |
101
102**Example**
103
104```js
105import { BusinessError } from '@kit.BasicServicesKit';
106
107try {
108    backgroundTaskManager.resetAllEfficiencyResources();
109} catch (error) {
110    console.error(`resetAllEfficiencyResources failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
111}
112```
113
114## backgroundTaskManager.getAllEfficiencyResources<sup>20+</sup>
115
116getAllEfficiencyResources(): Promise&lt;EfficiencyResourcesInfo[]&gt;
117
118Obtains all information about the requested efficiency resources, including the resource type. This API uses a promise to return the result.
119
120**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply
121
122**System API**: This is a system API.
123
124**Return value**
125
126| Type                                           | Description         |
127|-----------------------------------------------|-------------|
128|  Promise&lt;[EfficiencyResourcesInfo](#efficiencyresourcesinfo20)[]&gt; | Promise used to return all information about efficiency resources.|
129
130**Error codes**
131
132For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md).
133
134| ID | Error Message            |
135| ---- | --------------------- |
136| 202 | Not System App. |
137| 18700001 | Caller information verification failed for an energy resource request. |
138| 18700002 | Failed to write data into parcel. Possible reasons: 1. Invalid parameters; 2. Failed to apply for memory. |
139| 18700004 | System service operation failed. |
140
141**Example**
142
143```js
144import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
145import { BusinessError } from '@kit.BasicServicesKit';
146
147try {
148    backgroundTaskManager.getAllEfficiencyResources().then((res: backgroundTaskManager.EfficiencyResourcesInfo[]) => {
149        console.info(`Operation getAllEfficiencyResources succeeded. data: ` + JSON.stringify(res));
150    }).catch((error : BusinessError) => {
151        console.error(`Operation getAllEfficiencyResources failed. code is ${error.code} message is ${error.message}`);
152    });
153} catch (error) {
154    console.error(`Operation getAllEfficiencyResources failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
155}
156```
157
158## BackgroundMode
159
160Enumerates the continuous task modes.
161
162**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
163
164| Name                    | Value | Description                   |
165| ----------------------- | ---- | --------------------- |
166| WIFI_INTERACTION        | 7    | WLAN-related.<br>**System API**: This is a system API.|
167
168## EfficiencyResourcesRequest
169
170Describes the parameters for requesting efficiency resources.
171
172**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply
173
174**System API**: This is a system API.
175
176| Name            | Type    | Read-Only  | Optional  | Description                                      |
177| --------------- | ------ | ---- | ---- | ---------------------------------------- |
178| resourceTypes   | number  | No   | No   | Type of the resource to request.                              |
179| isApply         | boolean | No   | No   | Whether the request is used to apply for resources.<br>- **true**: The request is used to apply for resources.<br>- **false**: The request is used to release resources.|
180| timeOut         | number  | No   | No   | Duration for which the resource will be used, in milliseconds.               |
181| isPersist       | boolean | No   | Yes   | Whether the resource is permanently held. The default value is **false**.<br>- **true**: The resource is permanently held.<br>- **false**: The resource is held for a limited period of time.|
182| isProcess       | boolean | No   | Yes   | Whether the request is initiated by a process. The default value is **false**.<br>- **true**: The request is initiated by a process.<br>- **false**: The request is initiated by an application.        |
183| reason          | string  | No   | No   | Reason for requesting the resource.               |
184
185## ResourceType
186
187Enumerates the efficiency resource types.
188
189**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply
190
191**System API**: This is a system API.
192
193| Name                    | Value | Description                   |
194| ----------------------- | ---- | --------------------- |
195| CPU                     | 1    | CPU resource. Such type of resource prevents an application from being suspended.            |
196| COMMON_EVENT            | 2    | Common event resource. Such type of resource ensures that an application in the suspended state can receive common events.|
197| TIMER                   | 4    | Timer resource. Such type of resource ensures that an application in the suspended state can be woken up by system timers.|
198| WORK_SCHEDULER          | 8    | Deferred task resource. Such type of resource provides a loose control policy for an application.|
199| BLUETOOTH               | 16   | Bluetooth resource. Such type of resource ensures that an application in the suspended state can be woken up by Bluetooth-related events.|
200| GPS                     | 32   | GPS resource. Such type of resource ensures that an application in the suspended state can be woken up by GPS-related events.|
201| AUDIO                   | 64   | Audio resource. Such type of resource prevents an application from being suspended when the application has an audio being played.|
202| RUNNING_LOCK<sup>10+</sup> | 128 | RUNNING_LOCK resources are not proxied when the application is suspended.|
203| SENSOR<sup>10+</sup> | 256 | Sensor callbacks are not intercepted.|
204
205## EfficiencyResourcesInfo<sup>20+</sup>
206
207Efficiency resource information.
208
209**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply
210
211**System API**: This is a system API.
212
213| Name                            | Type     | Read-Only  | Optional  | Description         |
214|--------------------------------|---------| ---- | ---- |-------------|
215| [resourceTypes](#resourcetype) | number  | No   | No   | Enumerates the efficiency resource types.    |
216| timeout                        | number  | No   | No   | Timeout, in milliseconds.|
217| isPersistent                   | boolean | No   | No   | Whether the resource is permanently held. The default value is **false**. The value **true** indicates the resource is permanently held. The value **false** indicates that the resource is held within a limited time.     |
218| isForProcess                   | boolean | No   | No   | Whether the resource is requested by a process or an application. The value **true** indicates that the resource is requested by a process. The value **false** indicates that the resource is requested by an application.  |
219| reason                         | string  | No   | No   | Reason for requesting the resource.      |
220| uid                            | number  | No   | No   | Application UID.    |
221| pid                            | number  | No   | No   | Application PID.  |
222