js-apis-backgroundTaskManager.md 12.5 KB
Newer Older
W
wusongqing 已提交
1 2
# Background Task Management

W
wusongqing 已提交
3
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
W
wusongqing 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
> 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.


## Modules to Import

```
import backgroundTaskManager from '@ohos.backgroundTaskManager';  
```


## backgroundTaskManager.requestSuspendDelay

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

Requests delayed suspension after the application switches to the background.

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

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

W
wusongqing 已提交
24
**Parameters**
H
HelloCrease 已提交
25 26 27 28
| Name     | Type                 | Mandatory | Description                              |
| -------- | -------------------- | --------- | ---------------------------------------- |
| reason   | string               | Yes       | Reason for delayed transition to the suspended state. |
| 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 已提交
29

W
wusongqing 已提交
30
**Return value**
H
HelloCrease 已提交
31 32 33
| Type                                  | Description                             |
| ------------------------------------- | --------------------------------------- |
| [DelaySuspendInfo](#delaysuspendinfo) | Information about the suspension delay. |
W
wusongqing 已提交
34

W
wusongqing 已提交
35 36
**Example**
  ```js
W
wusongqing 已提交
37 38 39 40 41 42 43 44 45 46 47
  let myReason = 'test requestSuspendDelay';
  let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
      console.info("Request suspension delay will time out.");
  })
  ```


## backgroundTaskManager.getRemainingDelayTime

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

W
wusongqing 已提交
48 49 50
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 已提交
51

W
wusongqing 已提交
52
**Parameters**
H
HelloCrease 已提交
53 54 55 56
| Name      | Type                        | Mandatory | Description                              |
| --------- | --------------------------- | --------- | ---------------------------------------- |
| requestId | number                      | Yes       | ID of the suspension delay request.      |
| callback  | AsyncCallback<number> | Yes       | Callback used to return the remaining duration before the application is suspended, in milliseconds. |
W
wusongqing 已提交
57

W
wusongqing 已提交
58
**Example**
W
wusongqing 已提交
59

W
wusongqing 已提交
60
  ```js
W
wusongqing 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
  let id = 1;
  backgroundTaskManager.getRemainingDelayTime(id, (err, res) => {
      if(err.data === 0) {
          console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res));
      } else {
          console.log('promise => Operation failed. Cause: ' + err.data);
      }
  })
  ```


## backgroundTaskManager.getRemainingDelayTime

getRemainingDelayTime(requestId: number): Promise<number>

W
wusongqing 已提交
76 77 78
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 已提交
79

W
wusongqing 已提交
80
**Parameters**
H
HelloCrease 已提交
81 82 83
| Name      | Type   | Mandatory | Description                         |
| --------- | ------ | --------- | ----------------------------------- |
| requestId | number | Yes       | ID of the suspension delay request. |
W
wusongqing 已提交
84

W
wusongqing 已提交
85
**Return value**
H
HelloCrease 已提交
86 87 88
| Type                  | Description                              |
| --------------------- | ---------------------------------------- |
| Promise<number> | Promise used to return the remaining duration before the application is suspended, in milliseconds. |
W
wusongqing 已提交
89

W
wusongqing 已提交
90 91
**Example**
  ```js
W
wusongqing 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  let id = 1;
  backgroundTaskManager.getRemainingDelayTime(id).then( res => {
      console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res));
  }).catch( err => {
      console.log('promise => Operation failed. Cause: ' + err.data);
  })
  ```


## backgroundTaskManager.cancelSuspendDelay

cancelSuspendDelay(requestId: number): void

Cancels the suspension delay.

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

W
wusongqing 已提交
109
**Parameters**
H
HelloCrease 已提交
110 111 112
| Name      | Type   | Mandatory | Description                         |
| --------- | ------ | --------- | ----------------------------------- |
| requestId | number | Yes       | ID of the suspension delay request. |
W
wusongqing 已提交
113

W
wusongqing 已提交
114 115
**Example**
  ```js
W
wusongqing 已提交
116 117 118 119
  backgroundTaskManager.cancelSuspendDelay(id);
  ```


W
wusongqing 已提交
120
## backgroundTaskManager.startBackgroundRunning<sup>8+</sup>
W
wusongqing 已提交
121

W
wusongqing 已提交
122
startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback&lt;void&gt;): void
W
wusongqing 已提交
123 124 125

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

W
wusongqing 已提交
126 127
**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING

W
wusongqing 已提交
128 129
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask

W
wusongqing 已提交
130
**Parameters**
H
HelloCrease 已提交
131 132 133 134 135 136
| Name      | Type                               | Mandatory | Description                              |
| --------- | ---------------------------------- | --------- | ---------------------------------------- |
| context   | [Context](js-apis-Context.md)      | Yes       | Application context.                     |
| bgMode    | [BackgroundMode](#backgroundmode8) | Yes       | Background mode requested.               |
| 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. |
| callback  | AsyncCallback&lt;void&gt;          | Yes       | Callback used to return the result.      |
W
wusongqing 已提交
137

W
wusongqing 已提交
138
**Example**
W
wusongqing 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.wantAgent';

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

let wantAgentInfo = {
    wants: [
        {
            bundleName: "com.example.myapplication",
            abilityName: "com.example.myapplication.MainAbility"
        }
    ],
    operationType: wantAgent.OperationType.START_ABILITY,
    requestCode: 0,
    wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG]
};

wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
    backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
        backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj, callback)
});

```

W
wusongqing 已提交
171
## backgroundTaskManager.startBackgroundRunning<sup>8+</sup>
W
wusongqing 已提交
172

W
wusongqing 已提交
173
startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise&lt;void&gt;
W
wusongqing 已提交
174 175 176

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

W
wusongqing 已提交
177 178
**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING

W
wusongqing 已提交
179 180
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask

W
wusongqing 已提交
181
**Parameters**
W
wusongqing 已提交
182

H
HelloCrease 已提交
183 184 185 186 187
| Name      | Type                               | Mandatory | Description                              |
| --------- | ---------------------------------- | --------- | ---------------------------------------- |
| context   | [Context](js-apis-Context.md)      | Yes       | Application context.                     |
| bgMode    | [BackgroundMode](#backgroundmode8) | Yes       | Background mode requested.               |
| wantAgent | [WantAgent](js-apis-wantAgent.md)  | Yes       | Notification parameter, which is used to specify the target page when a continuous task notification is clicked. |
W
wusongqing 已提交
188

W
wusongqing 已提交
189
**Return value**
H
HelloCrease 已提交
190 191 192
| Type           | Description                        |
| -------------- | ---------------------------------- |
| Promise\<void> | Promise used to return the result. |
W
wusongqing 已提交
193

W
wusongqing 已提交
194
**Example**
W
wusongqing 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.wantAgent';

let wantAgentInfo = {
    wants: [
        {
            bundleName: "com.example.myapplication",
            abilityName: "com.example.myapplication.MainAbility"
        }
    ],
    operationType: wantAgent.OperationType.START_ABILITY,
    requestCode: 0,
    wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG]
};

wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
    backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
        backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
        console.info("Operation succeeded");
    }).catch((err) => {
        console.error("Operation failed Cause: " + err);
    });
});

```

W
wusongqing 已提交
223
## backgroundTaskManager.stopBackgroundRunning<sup>8+</sup>
W
wusongqing 已提交
224

W
wusongqing 已提交
225
stopBackgroundRunning(context: Context, callback: AsyncCallback&lt;void&gt;): void
W
wusongqing 已提交
226 227 228 229 230

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

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

W
wusongqing 已提交
231
**Parameters**
H
HelloCrease 已提交
232 233 234 235
| Name     | Type                          | Mandatory | Description                         |
| -------- | ----------------------------- | --------- | ----------------------------------- |
| context  | [Context](js-apis-Context.md) | Yes       | Application context.                |
| callback | AsyncCallback&lt;void&gt;     | Yes       | Callback used to return the result. |
W
wusongqing 已提交
236

W
wusongqing 已提交
237
**Example**
W
wusongqing 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';

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

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

```

W
wusongqing 已提交
254
## backgroundTaskManager.stopBackgroundRunning<sup>8+</sup>
W
wusongqing 已提交
255

W
wusongqing 已提交
256
stopBackgroundRunning(context: Context): Promise&lt;void&gt;
W
wusongqing 已提交
257 258 259 260 261

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

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

W
wusongqing 已提交
262
**Parameters**
H
HelloCrease 已提交
263 264 265
| Name    | Type                          | Mandatory | Description          |
| ------- | ----------------------------- | --------- | -------------------- |
| context | [Context](js-apis-Context.md) | Yes       | Application context. |
W
wusongqing 已提交
266

W
wusongqing 已提交
267
**Return value**
H
HelloCrease 已提交
268 269 270
| Type           | Description                        |
| -------------- | ---------------------------------- |
| Promise\<void> | Promise used to return the result. |
W
wusongqing 已提交
271

W
wusongqing 已提交
272
**Example**
W
wusongqing 已提交
273 274 275 276 277 278 279 280 281 282 283 284
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';

backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
    console.info("Operation succeeded");
}).catch((err) => {
    console.error("Operation failed Cause: " + err);
});

```

W
wusongqing 已提交
285 286 287 288 289 290
## DelaySuspendInfo

Provides the information about the suspension delay.

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

H
HelloCrease 已提交
291 292 293 294
| 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 已提交
295 296


W
wusongqing 已提交
297 298
## BackgroundMode<sup>8+</sup>

W
wusongqing 已提交
299
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
W
wusongqing 已提交
300

H
HelloCrease 已提交
301 302 303 304 305 306 307 308 309 310 311
| 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 (reserved).         |
| VOIP                    | 8     | Voice and video call (reserved). |
| TASK_KEEPING            | 9     | Computing task.                  |