js-apis-backgroundTaskManager.md 19.0 KB
Newer Older
1
# @ohos.backgroundTaskManager (Background Task Management)
W
wusongqing 已提交
2

W
wusongqing 已提交
3
The **BackgroundTaskManager** module provides APIs to manage background tasks.
W
wusongqing 已提交
4

G
Gloria 已提交
5
If 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.
W
wusongqing 已提交
6 7 8 9

If 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.

If 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.
W
wusongqing 已提交
10

11
If 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.
G
Gloria 已提交
12 13

>  **NOTE**
14 15
> - This module is deprecated since API version 9. You are advised to use [@ohos.resourceschedule.backgroundTaskManager](js-apis-resourceschedule-backgroundTaskManager.md) instead.
> - 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.
W
wusongqing 已提交
16 17 18 19


## Modules to Import

W
wusongqing 已提交
20
```js
W
wusongqing 已提交
21 22 23 24 25 26 27 28 29 30
import backgroundTaskManager from '@ohos.backgroundTaskManager';  
```


## backgroundTaskManager.requestSuspendDelay

requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspendInfo

Requests delayed suspension after the application switches to the background.

31
The 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.
W
wusongqing 已提交
32

W
wusongqing 已提交
33 34
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask

W
wusongqing 已提交
35
**Parameters**
36

W
wusongqing 已提交
37 38 39
| Name     | Type                  | Mandatory  | Description                            |
| -------- | -------------------- | ---- | ------------------------------ |
| reason   | string               | Yes   | Reason for delayed transition to the suspended state.                    |
W
wusongqing 已提交
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.|
W
wusongqing 已提交
41

W
wusongqing 已提交
42
**Return value**
43

W
wusongqing 已提交
44 45 46
| Type                                   | Description       |
| ------------------------------------- | --------- |
| [DelaySuspendInfo](#delaysuspendinfo) | Information about the suspension delay.|
W
wusongqing 已提交
47

W
wusongqing 已提交
48
**Example**
W
wusongqing 已提交
49

W
wusongqing 已提交
50
  ```js
51 52
  import backgroundTaskManager from '@ohos.backgroundTaskManager';

W
wusongqing 已提交
53 54 55 56
  let myReason = 'test requestSuspendDelay';
  let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
      console.info("Request suspension delay will time out.");
  })
57 58 59

  let id = delayInfo.requestId;
  let time = delayInfo.actualDelayTime;
W
wusongqing 已提交
60 61
  console.info("The requestId is: " + id);
  console.info("The actualDelayTime is: " + time);
W
wusongqing 已提交
62 63 64 65 66 67 68
  ```


## backgroundTaskManager.getRemainingDelayTime

getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void

W
wusongqing 已提交
69 70 71
Obtains the remaining duration before the application is suspended. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
W
wusongqing 已提交
72

W
wusongqing 已提交
73
**Parameters**
74

W
wusongqing 已提交
75 76
| Name      | Type                         | Mandatory  | Description                                      |
| --------- | --------------------------- | ---- | ---------------------------------------- |
77
| requestId | number                      | Yes   | ID of the suspension delay request. The value is obtained by calling [requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay).|
W
wusongqing 已提交
78
| callback  | AsyncCallback<number> | Yes   | Callback used to return the remaining duration before the application is suspended, in milliseconds.|
W
wusongqing 已提交
79

W
wusongqing 已提交
80
**Example**
W
wusongqing 已提交
81

W
wusongqing 已提交
82
  ```js
83 84 85 86
  import backgroundTaskManager from '@ohos.backgroundTaskManager';

  let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {});
  backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId, (err, res) => {
W
wusongqing 已提交
87 88
      if(err) {
          console.log('callback => Operation getRemainingDelayTime failed. Cause: ' + err.code);
W
wusongqing 已提交
89
      } else {
W
wusongqing 已提交
90
          console.log('callback => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
W
wusongqing 已提交
91 92 93 94 95 96 97 98 99
      }
  })
  ```


## backgroundTaskManager.getRemainingDelayTime

getRemainingDelayTime(requestId: number): Promise<number>

W
wusongqing 已提交
100 101 102
Obtains the remaining duration before the application is suspended. This API uses a promise to return the result.

**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
W
wusongqing 已提交
103

W
wusongqing 已提交
104
**Parameters**
105

W
wusongqing 已提交
106 107
| Name      | Type    | Mandatory  | Description        |
| --------- | ------ | ---- | ---------- |
108
| requestId | number | Yes   | ID of the suspension delay request. The value is obtained by calling [requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay).|
W
wusongqing 已提交
109

W
wusongqing 已提交
110
**Return value**
111

W
wusongqing 已提交
112
| Type                   | Description                                      |
H
HelloCrease 已提交
113
| --------------------- | ---------------------------------------- |
W
wusongqing 已提交
114
| Promise<number> | Promise used to return the remaining duration before the application is suspended, in milliseconds.|
W
wusongqing 已提交
115

W
wusongqing 已提交
116
**Example**
117

W
wusongqing 已提交
118
  ```js
119 120
  let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {});
  backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId).then( res => {
W
wusongqing 已提交
121
      console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
W
wusongqing 已提交
122
  }).catch( err => {
W
wusongqing 已提交
123
      console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code);
W
wusongqing 已提交
124 125 126 127 128 129 130 131 132 133
  })
  ```


## backgroundTaskManager.cancelSuspendDelay

cancelSuspendDelay(requestId: number): void

Cancels the suspension delay.

W
wusongqing 已提交
134 135
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask

W
wusongqing 已提交
136
**Parameters**
137

W
wusongqing 已提交
138 139
| Name      | Type    | Mandatory  | Description        |
| --------- | ------ | ---- | ---------- |
140
| requestId | number | Yes   | ID of the suspension delay request. The value is obtained by calling [requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay).|
W
wusongqing 已提交
141

W
wusongqing 已提交
142
**Example**
143

W
wusongqing 已提交
144
  ```js
145 146
  let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {});
  backgroundTaskManager.cancelSuspendDelay(delayInfo.requestId);
W
wusongqing 已提交
147 148 149
  ```


W
wusongqing 已提交
150
## backgroundTaskManager.startBackgroundRunning<sup>8+</sup>
W
wusongqing 已提交
151

W
wusongqing 已提交
152
startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback&lt;void&gt;): void
W
wusongqing 已提交
153 154 155

Requests a continuous task from the system. This API uses an asynchronous callback to return the result.

W
wusongqing 已提交
156 157
**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING

W
wusongqing 已提交
158 159
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask

W
wusongqing 已提交
160
**Parameters**
161

162 163 164 165 166 167
| Name   | Type                                         | Mandatory| Description                                                        |
| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| 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-ability-context.md).|
| bgMode    | [BackgroundMode](#backgroundmode8)            | Yes  | Background mode requested.                                      |
| 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.            |
| callback  | AsyncCallback&lt;void&gt;                     | Yes  | Callback used to return the result.                        |
W
wusongqing 已提交
168

W
wusongqing 已提交
169
**Example**
170 171 172

FA model:

W
wusongqing 已提交
173 174 175 176 177 178 179
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.wantAgent';

function callback(err, data) {
    if (err) {
W
wusongqing 已提交
180
        console.error("Operation startBackgroundRunning failed Cause: " + err);
W
wusongqing 已提交
181
    } else {
W
wusongqing 已提交
182
        console.info("Operation startBackgroundRunning succeeded");
W
wusongqing 已提交
183 184 185 186 187 188 189
    }
}

let wantAgentInfo = {
    wants: [
        {
            bundleName: "com.example.myapplication",
190
            abilityName: "EntryAbility"
W
wusongqing 已提交
191 192 193 194
        }
    ],
    operationType: wantAgent.OperationType.START_ABILITY,
    requestCode: 0,
W
wusongqing 已提交
195
    wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
W
wusongqing 已提交
196 197 198 199
};

wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
    backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
200
        backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback)
W
wusongqing 已提交
201 202 203 204
});

```

205 206 207
Stage model:

```ts
208
import UIAbility from '@ohos.app.ability.UIAbility';
209 210 211 212 213 214 215 216 217 218 219
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import wantAgent from '@ohos.wantAgent';

function callback(err, data) {
    if (err) {
        console.error("Operation startBackgroundRunning failed Cause: " + err);
    } else {
        console.info("Operation startBackgroundRunning succeeded");
    }
}

220
export default class EntryAbility extends UIAbility {
221 222 223 224 225
    onCreate(want, launchParam) {
        let wantAgentInfo = {
            wants: [
                {
                    bundleName: "com.example.myapplication",
226
                    abilityName: "EntryAbility"
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
                }
            ],
            operationType: wantAgent.OperationType.START_ABILITY,
            requestCode: 0,
            wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
        };

        wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
            backgroundTaskManager.startBackgroundRunning(this.context,
                backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback)
        });
    }
};
```

W
wusongqing 已提交
242
## backgroundTaskManager.startBackgroundRunning<sup>8+</sup>
W
wusongqing 已提交
243

W
wusongqing 已提交
244
startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise&lt;void&gt;
W
wusongqing 已提交
245 246 247

Requests a continuous task from the system. This API uses a promise to return the result.

W
wusongqing 已提交
248 249
**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING

W
wusongqing 已提交
250 251
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask

W
wusongqing 已提交
252
**Parameters**
W
wusongqing 已提交
253

254 255 256 257 258
| Name   | Type                                         | Mandatory| Description                                                        |
| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| 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-ability-context.md).|
| bgMode    | [BackgroundMode](#backgroundmode8)            | Yes  | Background mode requested.                                      |
| 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.              |
W
wusongqing 已提交
259

W
wusongqing 已提交
260
**Return value**
261

W
wusongqing 已提交
262
| Type            | Description              |
W
wusongqing 已提交
263
| -------------- | ---------------- |
W
wusongqing 已提交
264
| Promise\<void> | Promise used to return the result.|
W
wusongqing 已提交
265

W
wusongqing 已提交
266
**Example**
267 268 269

FA model:

W
wusongqing 已提交
270 271 272 273 274 275 276 277 278
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.wantAgent';

let wantAgentInfo = {
    wants: [
        {
            bundleName: "com.example.myapplication",
279
            abilityName: "EntryAbility"
W
wusongqing 已提交
280 281 282 283
        }
    ],
    operationType: wantAgent.OperationType.START_ABILITY,
    requestCode: 0,
W
wusongqing 已提交
284
    wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
W
wusongqing 已提交
285 286 287 288
};

wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
    backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
289
        backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => {
W
wusongqing 已提交
290
        console.info("Operation startBackgroundRunning succeeded");
W
wusongqing 已提交
291
    }).catch((err) => {
W
wusongqing 已提交
292
        console.error("Operation startBackgroundRunning failed Cause: " + err);
W
wusongqing 已提交
293 294
    });
});
295 296 297 298 299
```

Stage model:

```ts
300
import UIAbility from '@ohos.app.ability.UIAbility';
301 302
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import wantAgent from '@ohos.wantAgent';
W
wusongqing 已提交
303

304
export default class EntryAbility extends UIAbility {
305 306 307 308 309
    onCreate(want, launchParam) {
        let wantAgentInfo = {
            wants: [
                {
                    bundleName: "com.example.myapplication",
310
                    abilityName: "EntryAbility"
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
                }
            ],
            operationType: wantAgent.OperationType.START_ABILITY,
            requestCode: 0,
            wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
        };

        wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
            backgroundTaskManager.startBackgroundRunning(this.context,
                backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => {
                console.info("Operation startBackgroundRunning succeeded");
            }).catch((err) => {
                console.error("Operation startBackgroundRunning failed Cause: " + err);
            });
        });
    }
};
W
wusongqing 已提交
328 329
```

W
wusongqing 已提交
330
## backgroundTaskManager.stopBackgroundRunning<sup>8+</sup>
W
wusongqing 已提交
331

W
wusongqing 已提交
332
stopBackgroundRunning(context: Context, callback: AsyncCallback&lt;void&gt;): void
W
wusongqing 已提交
333 334 335 336 337

Requests to cancel a continuous task. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask

W
wusongqing 已提交
338
**Parameters**
339

W
wusongqing 已提交
340 341
| Name     | Type                       | Mandatory  | Description                                      |
| -------- | ------------------------- | ---- | ---------------------------------------- |
342
| 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-ability-context.md).|
W
wusongqing 已提交
343
| callback | AsyncCallback&lt;void&gt; | Yes   | Callback used to return the result.                  |
W
wusongqing 已提交
344

W
wusongqing 已提交
345
**Example**
346 347 348

FA model:

W
wusongqing 已提交
349 350 351 352 353 354
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';

function callback(err, data) {
    if (err) {
W
wusongqing 已提交
355
        console.error("Operation stopBackgroundRunning failed Cause: " + err);
W
wusongqing 已提交
356
    } else {
W
wusongqing 已提交
357
        console.info("Operation stopBackgroundRunning succeeded");
W
wusongqing 已提交
358 359 360 361 362 363 364
    }
}

backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), callback);

```

365 366 367
Stage model:

```ts
368
import UIAbility from '@ohos.app.ability.UIAbility';
369 370 371 372 373 374 375 376 377 378
import backgroundTaskManager from '@ohos.backgroundTaskManager';

function callback(err, data) {
    if (err) {
        console.error("Operation stopBackgroundRunning failed Cause: " + err);
    } else {
        console.info("Operation stopBackgroundRunning succeeded");
    }
}

379
export default class EntryAbility extends UIAbility {
380 381 382 383 384 385
    onCreate(want, launchParam) {
        backgroundTaskManager.stopBackgroundRunning(this.context, callback);
    }
};
```

W
wusongqing 已提交
386
## backgroundTaskManager.stopBackgroundRunning<sup>8+</sup>
W
wusongqing 已提交
387

W
wusongqing 已提交
388
stopBackgroundRunning(context: Context): Promise&lt;void&gt;
W
wusongqing 已提交
389 390 391 392 393

Requests to cancel a continuous task. This API uses a promise to return the result.

**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask

W
wusongqing 已提交
394
**Parameters**
395

W
wusongqing 已提交
396 397
| Name    | Type     | Mandatory  | Description                                      |
| ------- | ------- | ---- | ---------------------------------------- |
398
| 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-ability-context.md).|
W
wusongqing 已提交
399

W
wusongqing 已提交
400
**Return value**
401

W
wusongqing 已提交
402
| Type            | Description              |
W
wusongqing 已提交
403
| -------------- | ---------------- |
W
wusongqing 已提交
404
| Promise\<void> | Promise used to return the result.|
W
wusongqing 已提交
405

W
wusongqing 已提交
406
**Example**
407 408 409

FA model:

W
wusongqing 已提交
410 411 412 413 414
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';

backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
W
wusongqing 已提交
415
    console.info("Operation stopBackgroundRunning succeeded");
W
wusongqing 已提交
416
}).catch((err) => {
W
wusongqing 已提交
417
    console.error("Operation stopBackgroundRunning failed Cause: " + err);
W
wusongqing 已提交
418 419 420 421
});

```

422
Stage model:
G
Gloria 已提交
423

424
```ts
425
import UIAbility from '@ohos.app.ability.UIAbility';
G
Gloria 已提交
426 427
import backgroundTaskManager from '@ohos.backgroundTaskManager';

428
export default class EntryAbility extends UIAbility {
429 430 431 432 433 434 435
    onCreate(want, launchParam) {
        backgroundTaskManager.stopBackgroundRunning(this.context).then(() => {
            console.info("Operation stopBackgroundRunning succeeded");
        }).catch((err) => {
            console.error("Operation stopBackgroundRunning failed Cause: " + err);
        });
    }
G
Gloria 已提交
436 437 438
};
```

W
wusongqing 已提交
439 440 441 442 443 444
## DelaySuspendInfo

Provides the information about the suspension delay.

**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask

W
wusongqing 已提交
445 446 447 448
| Name            | Type    | Mandatory  | Description                                      |
| --------------- | ------ | ---- | ---------------------------------------- |
| requestId       | number | Yes   | ID of the suspension delay request.                              |
| 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.|
W
wusongqing 已提交
449 450


W
wusongqing 已提交
451 452
## BackgroundMode<sup>8+</sup>

W
wusongqing 已提交
453
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
W
wusongqing 已提交
454

455 456 457 458 459 460 461 462 463 464 465
| Name                    | Value | Description                   |
| ----------------------- | ---- | --------------------- |
| DATA_TRANSFER           | 1    | Data transfer.                 |
| AUDIO_PLAYBACK          | 2    | Audio playback.                 |
| AUDIO_RECORDING         | 3    | Audio recording.                   |
| LOCATION                | 4    | Positioning and navigation.                 |
| BLUETOOTH_INTERACTION   | 5    | Bluetooth-related task.                 |
| MULTI_DEVICE_CONNECTION | 6    | Multi-device connection.                |
| WIFI_INTERACTION        | 7    | WLAN-related.<br>This is a system API.|
| VOIP                    | 8    | Audio and video calls.<br>This is a system API. |
| TASK_KEEPING            | 9    | Computing task (effective only for specific devices).       |